import { useEffect, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { useHomeowner } from "@/contexts/HomeownerContext";
import { Card, CardContent } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { FileText, Search, ExternalLink } from "lucide-react";
import { format } from "date-fns";

interface Document {
  id: string;
  title: string;
  file_name: string | null;
  file_url: string | null;
  category: string | null;
  visibility: string[];
  created_at: string;
}

export default function ClientDocumentsPage() {
  const { association } = useHomeowner();
  const [documents, setDocuments] = useState<Document[]>([]);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState("");

  useEffect(() => {
    if (!association?.id) {
      setLoading(false);
      return;
    }

    const fetchDocs = async () => {
      setLoading(true);
      const { data, error } = await supabase
        .from("documents")
        .select("id, title, file_name, file_url, category, visibility, created_at")
        .eq("association_id", association.id)
        .or("visibility.cs.{homeowner},visibility.cs.{public},is_public.eq.true")
        .order("created_at", { ascending: false });

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

    fetchDocs();
  }, [association?.id]);

  const filteredDocs = documents.filter((d) => {
    if (search) {
      const q = search.toLowerCase();
      return (
        d.title.toLowerCase().includes(q) ||
        (d.file_name || "").toLowerCase().includes(q) ||
        (d.category || "").toLowerCase().includes(q)
      );
    }
    return true;
  });

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

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold text-foreground">Documents</h1>
        <p className="text-muted-foreground mt-1">
          View documents shared by your association.
        </p>
      </div>

      {/* Search */}
      <div className="relative max-w-md">
        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
        <Input
          placeholder="Search documents..."
          className="pl-9"
          value={search}
          onChange={(e) => setSearch(e.target.value)}
        />
      </div>

      {documents.length === 0 ? (
        <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 available yet.</p>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-3">
          <h2 className="text-lg font-semibold text-foreground">
            {association?.name || "Association Documents"}
          </h2>

          {filteredDocs.length === 0 ? (
            <p className="text-sm text-muted-foreground py-4">
              No documents match your search.
            </p>
          ) : (
            <div className="grid gap-2">
              {filteredDocs.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.file_name && (
                            <span className="truncate max-w-[200px]">
                              {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>
          )}
        </div>
      )}
    </div>
  );
}
