import React from 'react';
import { motion } from 'framer-motion';
import { format } from 'date-fns';
import { Edit2, Trash2, CalendarClock, Paperclip, FileImage as FileIcon, ExternalLink, AlertTriangle, DollarSign, Filter } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent,
  AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { supabase } from '@/integrations/supabase/client';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';

export function OwnerUpdateCard({ update, onEdit, onDeleteSuccess, onTagClick, selectedTags = [] }) {
  const { toast } = useToast();

  const handleDelete = async () => {
    try {
      const { error } = await supabase.from('owner_updates').delete().eq('id', update.id);
      if (error) throw error;
      toast({ title: "Deleted", description: "Update removed." });
      if (onDeleteSuccess) onDeleteSuccess();
    } catch (err) {
      console.error(err);
      toast({ variant: "destructive", title: "Error", description: "Failed to delete update." });
    }
  };

  const getColorClass = (color, isSelected) => {
    const baseClass = (() => {
      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';
      }
    })();
    return cn(baseClass, isSelected && "ring-2 ring-offset-1 ring-slate-400 font-medium");
  };

  const hasAttachments = update.attachments && Array.isArray(update.attachments) && update.attachments.length > 0;
  const violationCount = Array.isArray(update.violation_ids) ? update.violation_ids.length : 0;
  const collectionCount = Array.isArray(update.collection_ids) ? update.collection_ids.length : 0;
  const tags = Array.isArray(update.tags) ? update.tags : [];

  const unitAddress = update.units?.address || '';
  const unitNumber = update.units?.unit_number || '';
  const activeOwners = (update.units?.owners || []).filter(o => o.status !== 'archived');
  const ownerNames = activeOwners.map(o => [o.first_name, o.last_name].filter(Boolean).join(' ')).join(', ');

  return (
    <motion.div initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.95 }} layout className="group">
      <Card className="border-l-4 border-l-blue-500 shadow-sm hover:shadow-md transition-shadow overflow-visible">
        <CardContent className="p-4">
          {(unitNumber || unitAddress || ownerNames) && (
            <div className="flex flex-wrap items-center gap-x-3 gap-y-1 mb-2 text-sm">
              {unitNumber && (
                <span className="font-semibold text-foreground">Unit {unitNumber}</span>
              )}
              {unitAddress && (
                <span className="text-muted-foreground">{unitAddress}</span>
              )}
              {ownerNames && (
                <span className="text-muted-foreground">— {ownerNames}</span>
              )}
            </div>
          )}
          <div className="flex justify-between items-start mb-2">
            <div className="flex flex-wrap items-center gap-2">
              <div className="flex items-center text-sm text-muted-foreground gap-1">
                <CalendarClock className="w-4 h-4" />
                <span>{format(new Date(update.posted_at || update.created_at), "MMM d, yyyy 'at' h:mm a")}</span>
              </div>
              {(violationCount > 0 || collectionCount > 0) && (
                <div className="flex gap-2 ml-2">
                  {violationCount > 0 && (
                    <Badge variant="outline" className="text-xs gap-1 border-amber-200 bg-amber-50 text-amber-700 font-normal">
                      <AlertTriangle className="w-3 h-3" /> {violationCount} Violation{violationCount > 1 ? 's' : ''}
                    </Badge>
                  )}
                  {collectionCount > 0 && (
                    <Badge variant="outline" className="text-xs gap-1 border-green-200 bg-green-50 text-green-700 font-normal">
                      <DollarSign className="w-3 h-3" /> {collectionCount} Collection{collectionCount > 1 ? 's' : ''}
                    </Badge>
                  )}
                </div>
              )}
              {tags.length > 0 && (
                <div className="flex flex-wrap gap-1 ml-2">
                  {tags.map((tag, i) => {
                    const isSelected = selectedTags.includes(tag.name);
                    return (
                      <Badge key={i} variant="outline"
                        className={cn("cursor-pointer hover:opacity-80 transition-all", getColorClass(tag.color, isSelected))}
                        onClick={() => onTagClick && onTagClick(tag.name)}>
                        {isSelected && <Filter className="w-3 h-3 mr-1" />}{tag.name}
                      </Badge>
                    );
                  })}
                </div>
              )}
            </div>
            <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
              <Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-primary" onClick={() => onEdit(update)}>
                <Edit2 className="w-4 h-4" />
              </Button>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button size="icon" variant="ghost" className="h-8 w-8 text-muted-foreground hover:text-destructive">
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Delete Update?</AlertDialogTitle>
                    <AlertDialogDescription>This action cannot be undone.</AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleDelete} className="bg-destructive hover:bg-destructive/90 text-destructive-foreground">Delete</AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          </div>

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

          {hasAttachments && (
            <div className="mt-4 pt-3 border-t">
              <h4 className="text-xs font-semibold text-muted-foreground mb-2 flex items-center gap-1">
                <Paperclip className="w-3 h-3" /> Attachments ({update.attachments.length})
              </h4>
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {update.attachments.map((file, idx) => (
                  <a key={idx} href={file.file_url} target="_blank" rel="noopener noreferrer"
                    className="flex items-center gap-2 p-2 rounded-md border bg-muted/30 hover:bg-muted/50 transition-colors group/file text-sm">
                    <div className="bg-background p-1.5 rounded border">
                      <FileIcon className="w-4 h-4 text-primary" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <p className="font-medium truncate">{file.file_name}</p>
                      <p className="text-[10px] text-muted-foreground">{file.file_size ? `${(file.file_size / 1024).toFixed(1)} KB` : 'File'}</p>
                    </div>
                    <ExternalLink className="w-3 h-3 text-muted-foreground group-hover/file:text-primary" />
                  </a>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </motion.div>
  );
}
