import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { FileText, Download, ExternalLink } from "lucide-react";
import { format } from "date-fns";

interface Props {
  unitId: string;
  associationId: string;
}

export default function LegalCaseDocumentsTab({ unitId, associationId }: Props) {
  const [documents, setDocuments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchDocs = async () => {
      setLoading(true);
      const { data, error } = await supabase
        .from("unit_documents")
        .select("*")
        .eq("unit_id", unitId)
        .order("created_at", { ascending: false });

      if (error) {
        console.error("Error fetching unit documents:", error);
      } else {
        setDocuments(data || []);
      }
      setLoading(false);
    };

    fetchDocs();
  }, [unitId]);

  if (loading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent" />
      </div>
    );
  }

  if (documents.length === 0) {
    return (
      <Card>
        <CardContent className="flex flex-col items-center justify-center py-16 text-muted-foreground">
          <FileText className="h-10 w-10 mb-3 opacity-30" />
          <p className="text-sm">No documents uploaded for this unit yet.</p>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="grid gap-2">
      {documents.map((doc) => (
        <Card key={doc.id} className="border-border">
          <CardContent className="p-3 flex items-center justify-between">
            <div className="flex items-center gap-3 min-w-0">
              <FileText className="h-5 w-5 text-primary flex-shrink-0" />
              <div className="min-w-0">
                <p className="text-sm font-medium text-foreground truncate">{doc.title}</p>
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  {doc.category && <Badge variant="outline" className="text-[10px]">{doc.category}</Badge>}
                  {doc.file_name && <span className="truncate">{doc.file_name}</span>}
                  <span>{format(new Date(doc.created_at), "MMM d, yyyy")}</span>
                </div>
              </div>
            </div>
            {doc.file_url && (
              <Button
                variant="ghost"
                size="icon"
                className="h-8 w-8 flex-shrink-0"
                onClick={() => window.open(doc.file_url, "_blank")}
              >
                <ExternalLink className="h-4 w-4" />
              </Button>
            )}
          </CardContent>
        </Card>
      ))}
    </div>
  );
}
