import React, { useState, useEffect } from 'react';
import { format } from 'date-fns';
import { motion } from 'framer-motion';
import { MapPin, Calendar, Paperclip, FileText, User, Download, AlertTriangle, DollarSign, ChevronDown, ChevronUp } from 'lucide-react';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { supabase } from '@/integrations/supabase/client';
import { cn } from '@/lib/utils';

export function OwnerUpdateDisplayCard({ update, onTagClick }) {
  const hasAttachments = update.attachments && Array.isArray(update.attachments) && update.attachments.length > 0;
  const unitAddress = update.units?.address || update.units?.unit_number || 'Unknown Unit';
  const creatorName = update.profiles?.full_name || 'System';

  const [linkedItems, setLinkedItems] = useState({ violations: [], collections: [] });
  const [showLinkedDetails, setShowLinkedDetails] = useState(false);
  const [loadingLinks, setLoadingLinks] = useState(false);

  const hasCollectionIds = update.collection_ids?.length > 0;
  const hasViolationIds = update.violation_ids?.length > 0;
  const hasLinkedItems = hasCollectionIds || hasViolationIds;
  const tags = Array.isArray(update.tags) ? update.tags : [];

  const getColorClass = (color) => {
    switch (color) {
      case 'red': return 'bg-red-100 text-red-700 border-red-200';
      case 'green': return 'bg-green-100 text-green-700 border-green-200';
      case 'amber': return 'bg-amber-100 text-amber-700 border-amber-200';
      case 'purple': return 'bg-purple-100 text-purple-700 border-purple-200';
      case 'slate': return 'bg-slate-100 text-slate-700 border-slate-200';
      default: return 'bg-blue-100 text-blue-700 border-blue-200';
    }
  };

  useEffect(() => {
    if ((hasCollectionIds || hasViolationIds) && showLinkedDetails && linkedItems.violations.length === 0 && linkedItems.collections.length === 0) {
      const fetchLinked = async () => {
        setLoadingLinks(true);
        try {
          let violations = [], collections = [];
          if (hasViolationIds) {
            const { data } = await supabase.from('violations').select('id, violation_type, status, created_at').in('id', update.violation_ids);
            violations = data || [];
          }
          if (hasCollectionIds) {
            const { data } = await supabase.from('collections').select('id, status, amount_owed').in('id', update.collection_ids);
            collections = data || [];
          }
          setLinkedItems({ violations, collections });
        } catch (err) {
          console.error("Error fetching linked items:", err);
        } finally {
          setLoadingLinks(false);
        }
      };
      fetchLinked();
    }
  }, [showLinkedDetails, hasCollectionIds, hasViolationIds]);

  return (
    <motion.div initial={{ opacity: 0, y: 15 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }} className="group">
      <Card className="overflow-hidden border hover:border-primary/30 hover:shadow-md transition-all duration-300">
        <CardHeader className="bg-muted/30 border-b p-4 pb-3">
          <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2">
            <div className="flex items-start gap-2.5 overflow-hidden">
              <div className="p-2 bg-background rounded-lg border shadow-sm shrink-0"><MapPin className="w-5 h-5 text-primary" /></div>
              <div className="min-w-0">
                <h3 className="font-semibold text-foreground text-lg truncate">{unitAddress}</h3>
              </div>
            </div>
            <Badge variant="outline" className="w-fit bg-background text-muted-foreground font-normal shrink-0 gap-1.5 pl-1.5">
              <Calendar className="w-3.5 h-3.5" />{format(new Date(update.posted_at || update.created_at), "MMM d, yyyy")}
            </Badge>
          </div>
        </CardHeader>
        <CardContent className="p-5">
          {tags.length > 0 && (
            <div className="flex overflow-x-auto pb-1 gap-2 mb-3">
              {tags.map((tag, i) => (
                <Badge key={i} variant="outline" className={cn("whitespace-nowrap cursor-pointer hover:opacity-80", getColorClass(tag.color))} onClick={() => onTagClick?.(tag.name)}>{tag.name}</Badge>
              ))}
            </div>
          )}

          {hasLinkedItems && (
            <div className="mb-4">
              <div className="flex flex-wrap items-center gap-2">
                {hasViolationIds && <Badge variant="outline" className="gap-1.5 border-amber-200 bg-amber-50 text-amber-700 font-normal"><AlertTriangle className="w-3.5 h-3.5" />{update.violation_ids.length} Violation(s)</Badge>}
                {hasCollectionIds && <Badge variant="outline" className="gap-1.5 border-green-200 bg-green-50 text-green-700 font-normal"><DollarSign className="w-3.5 h-3.5" />{update.collection_ids.length} Collection(s)</Badge>}
                <Button variant="ghost" size="sm" className="h-7 text-xs text-muted-foreground px-2" onClick={() => setShowLinkedDetails(!showLinkedDetails)}>
                  {showLinkedDetails ? "Hide" : "Details"} {showLinkedDetails ? <ChevronUp className="ml-1 w-3 h-3" /> : <ChevronDown className="ml-1 w-3 h-3" />}
                </Button>
              </div>
              {showLinkedDetails && (
                <div className="mt-3 space-y-3 bg-muted/30 p-3 rounded-lg border text-sm">
                  {loadingLinks ? <div className="text-xs text-muted-foreground text-center py-2">Loading...</div> : (
                    <>
                      {linkedItems.violations.length > 0 && (
                        <div className="space-y-2">
                          <p className="font-semibold text-muted-foreground text-[10px] uppercase tracking-wider">Violations</p>
                          {linkedItems.violations.map(v => (
                            <div key={v.id} className="flex justify-between items-center bg-background p-2.5 rounded border shadow-sm">
                              <div className="flex items-center gap-2"><AlertTriangle className="w-3.5 h-3.5 text-amber-500" /><span className="font-medium">{v.violation_type}</span></div>
                              <Badge variant="secondary" className="text-[10px] h-5">{v.status}</Badge>
                            </div>
                          ))}
                        </div>
                      )}
                      {linkedItems.collections.length > 0 && (
                        <div className="space-y-2">
                          <p className="font-semibold text-muted-foreground text-[10px] uppercase tracking-wider pt-1">Collections</p>
                          {linkedItems.collections.map(c => (
                            <div key={c.id} className="flex justify-between items-center bg-background p-2.5 rounded border shadow-sm">
                              <div className="flex items-center gap-2"><DollarSign className="w-3.5 h-3.5 text-green-600" /><span className="font-medium">{c.status}</span></div>
                              <span className="font-mono text-xs">${Number(c.amount_owed).toFixed(2)}</span>
                            </div>
                          ))}
                        </div>
                      )}
                    </>
                  )}
                </div>
              )}
            </div>
          )}

          <div className="prose prose-sm max-w-none text-foreground leading-relaxed mb-4" dangerouslySetInnerHTML={{ __html: update.content }} />

          <div className="flex flex-col gap-4 border-t pt-4">
            <div className="flex items-center gap-2 text-xs text-muted-foreground">
              <User className="w-3.5 h-3.5" /><span>Posted by <span className="font-medium text-foreground">{creatorName}</span></span>
            </div>
            {hasAttachments && (
              <div className="space-y-2">
                <h4 className="text-xs font-semibold uppercase tracking-wider text-muted-foreground flex items-center gap-1.5"><Paperclip className="w-3 h-3" />Attachments ({update.attachments.length})</h4>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  {update.attachments.map((file, idx) => (
                    <a key={idx} href={file.file_url} target="_blank" rel="noopener noreferrer" className="flex items-center gap-3 p-2.5 rounded-lg border bg-muted/30 hover:bg-background hover:border-primary/40 hover:shadow-sm transition-all group/file relative overflow-hidden">
                      <div className="p-2 bg-background rounded border shrink-0 text-primary"><FileText className="w-5 h-5" /></div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate pr-4">{file.file_name}</p>
                        <p className="text-[10px] text-muted-foreground">{file.file_size ? `${(file.file_size / 1024).toFixed(1)} KB` : 'Download'}</p>
                      </div>
                      <div className="opacity-0 group-hover/file:opacity-100 transition-opacity absolute right-2 bg-background/80 p-1 rounded-full"><Download className="w-4 h-4 text-primary" /></div>
                    </a>
                  ))}
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>
    </motion.div>
  );
}
