import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { MessageSquare, Loader2, RefreshCw, Eye } from "lucide-react";
import { format } from "date-fns";
import { Alert, AlertDescription } from "@/components/ui/alert";

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

export default function UnitOwnerUpdatesTab({ unitId, associationId }: Props) {
  const [updates, setUpdates] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [selectedUpdate, setSelectedUpdate] = useState<any | null>(null);

  const fetchUpdates = async () => {
    setLoading(true);
    setError(null);
    try {
      const { data, error: fetchError } = await supabase
        .from("owner_updates")
        .select("*")
        .eq("unit_id", unitId)
        .eq("association_id", associationId)
        .order("created_at", { ascending: false })
        .limit(50);

      if (fetchError) throw fetchError;
      setUpdates((data || []).filter((update) => update.unit_id === unitId));
    } catch (err: any) {
      console.error("Error fetching owner updates:", err);
      setError(err.message || "Failed to fetch updates");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (unitId) fetchUpdates();
  }, [unitId, associationId]);

  if (loading) return <div className="flex justify-center p-8"><Loader2 className="w-6 h-6 animate-spin text-muted-foreground" /></div>;

  if (error) {
    return (
      <Alert variant="destructive">
        <MessageSquare className="w-4 h-4" />
        <AlertDescription className="flex items-center justify-between">
          <span>{error}</span>
          <Button variant="outline" size="sm" onClick={fetchUpdates}><RefreshCw className="w-4 h-4 mr-2" /> Retry</Button>
        </AlertDescription>
      </Alert>
    );
  }

  return (
    <div className="space-y-4">
      {updates.length === 0 ? (
        <div className="text-center p-8 bg-muted rounded-lg border">
          <MessageSquare className="w-8 h-8 text-muted-foreground mx-auto mb-3" />
          <p className="font-medium">No Updates</p>
          <p className="text-sm text-muted-foreground mt-1">There are no recent owner updates for this unit.</p>
        </div>
      ) : (
        <div className="rounded-md border">
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Date</TableHead>
                <TableHead>Title</TableHead>
                <TableHead>Content Snippet</TableHead>
                <TableHead className="text-right">Actions</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {updates.map((update) => (
                <TableRow key={update.id}>
                  <TableCell className="whitespace-nowrap">
                    {update.created_at ? format(new Date(update.created_at), "MMM d, yyyy") : "N/A"}
                  </TableCell>
                  <TableCell className="font-medium">{update.title}</TableCell>
                  <TableCell className="max-w-xs truncate text-muted-foreground" title={update.content}>
                    {update.content || "No content"}
                  </TableCell>
                  <TableCell className="text-right">
                    <Button variant="ghost" size="sm" onClick={() => setSelectedUpdate(update)}>
                      <Eye className="w-4 h-4 mr-2" /> View
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </div>
      )}

      <Dialog open={!!selectedUpdate} onOpenChange={(open) => !open && setSelectedUpdate(null)}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <MessageSquare className="w-5 h-5 text-muted-foreground" /> Owner Update Details
            </DialogTitle>
            <DialogDescription>Details for the selected unit owner update.</DialogDescription>
          </DialogHeader>
          {selectedUpdate && (
            <div className="space-y-4 mt-4">
              <div className="grid grid-cols-2 gap-4 border-b pb-4">
                <div>
                  <p className="text-sm text-muted-foreground">Title</p>
                  <p className="font-medium">{selectedUpdate.title}</p>
                </div>
                <div>
                  <p className="text-sm text-muted-foreground">Date</p>
                  <p className="font-medium">{selectedUpdate.created_at ? format(new Date(selectedUpdate.created_at), "MMMM d, yyyy h:mm a") : "N/A"}</p>
                </div>
              </div>
              <div>
                <p className="text-sm text-muted-foreground mb-1">Content</p>
                <p className="bg-muted p-4 rounded-md border whitespace-pre-wrap">{selectedUpdate.content || "No content provided."}</p>
              </div>
            </div>
          )}
        </DialogContent>
      </Dialog>
    </div>
  );
}
