
import React, { useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { formatDateTimeShortEST } from '@/lib/timezoneUtils';
import { Edit, Trash2, User, Calendar, MessageSquare, Send, AlertCircle, ThumbsUp, ThumbsDown, Vote, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
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 { StatusUpdateImageThumbnail } from '@/components/status-updates/StatusUpdateImageThumbnail';

function StatusUpdateCard({ update, canManage, onEdit, onDelete, index, onRefresh, currentUserId }) {
  const { toast } = useToast();
  const [showComments, setShowComments] = useState(false);
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState('');
  const [loadingComments, setLoadingComments] = useState(false);
  const [submittingComment, setSubmittingComment] = useState(false);
  const [actionLoading, setActionLoading] = useState(false);

  if (!update) return null;

  const votes = update.status_update_votes || [];
  const approveVotes = votes.filter(v => v.vote === 'approve').length;
  const rejectVotes = votes.filter(v => v.vote === 'reject').length;
  const userVote = votes.find(v => v.user_id === currentUserId);

  const handleDelete = async () => {
    const { error } = await supabase.from('status_updates').delete().eq('id', update.id);
    if (error) {
      toast({ variant: 'destructive', title: 'Error deleting update', description: error.message });
    } else {
      toast({ title: 'Update Deleted', description: 'The status update has been successfully deleted.' });
      if (onDelete) onDelete();
    }
  };

  const fetchComments = async () => {
    setLoadingComments(true);
    const { data, error } = await supabase
      .from('status_update_comments')
      .select('*, profiles:user_id(email)')
      .eq('status_update_id', update.id)
      .order('created_at', { ascending: true });
    
    if (!error) {
      setComments(data || []);
    }
    setLoadingComments(false);
  };

  const handleToggleComments = () => {
    if (!showComments) {
      fetchComments();
    }
    setShowComments(!showComments);
  };

  const handleSubmitComment = async (e) => {
    e.preventDefault();
    if (!newComment.trim()) return;

    setSubmittingComment(true);
    const commentContent = newComment.trim();
    
    const { error } = await supabase.from('status_update_comments').insert({
      status_update_id: update.id,
      user_id: currentUserId,
      content: commentContent
    });

    if (error) {
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to post comment.' });
    } else {
      setNewComment('');
      fetchComments();
    }
    setSubmittingComment(false);
  };

  const handleToggleVoting = async () => {
    setActionLoading(true);
    const newVotingState = !update.voting_enabled;
    const { error } = await supabase
      .from('status_updates')
      .update({ voting_enabled: newVotingState })
      .eq('id', update.id);
    
    if (error) {
      toast({ variant: 'destructive', title: 'Error', description: error.message });
    } else {
      toast({ title: 'Success', description: `Voting ${newVotingState ? 'enabled' : 'disabled'}` });
      if (onRefresh) onRefresh();
    }
    setActionLoading(false);
  };

  const handleVote = async (voteType) => {
    setActionLoading(true);
    
    const existingVote = votes.find(v => v.user_id === currentUserId);
    let error;

    if (existingVote) {
      const { error: updateError } = await supabase
        .from('status_update_votes')
        .update({ vote: voteType })
        .eq('id', existingVote.id);
      error = updateError;
    } else {
      const { error: insertError } = await supabase
        .from('status_update_votes')
        .insert({
          status_update_id: update.id,
          user_id: currentUserId,
          vote: voteType
        });
      error = insertError;
    }

    if (error) {
      toast({ variant: 'destructive', title: 'Error', description: 'Failed to cast vote.' });
    } else {
      toast({ title: 'Vote Cast', description: `You voted to ${voteType} this update.` });
      if (onRefresh) onRefresh();
    }
    setActionLoading(false);
  };

  const formatDate = (dateString) => {
    if (!dateString) return 'Date N/A';
    try {
      const result = formatDateTimeShortEST(dateString);
      return result === '-' ? 'Invalid Date' : result;
    } catch (e) {
      return 'Invalid Date';
    }
  };

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: index * 0.05 }}
      className="bg-card rounded-lg shadow-md border border-border overflow-hidden"
    >
      <div className="p-4 md:p-5">
        <div className="flex flex-col sm:flex-row sm:justify-between sm:items-start gap-4">
          <div className="flex-1 min-w-0">
            {update.associations && <p className="text-sm font-semibold text-primary">{update.associations.name}</p>}
            <h3 className="text-xl font-bold text-foreground mt-1 break-words">{update.title}</h3>
          </div>
          {canManage && (
            <div className="flex items-center space-x-2 flex-shrink-0 self-start">
              <Button variant="outline" size="sm" onClick={onEdit}>
                <Edit className="w-4 h-4" />
              </Button>
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button variant="outline" size="sm" className="text-destructive hover:bg-destructive/10 hover:text-destructive">
                    <Trash2 className="w-4 h-4" />
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                      This will permanently delete the status update. This action cannot be undone.
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction onClick={handleDelete} className="bg-destructive text-destructive-foreground hover:bg-destructive/90">Delete</AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </div>
          )}
        </div>
        
        <div 
          className="text-foreground/90 mt-3 prose prose-sm max-w-none overflow-hidden"
          dangerouslySetInnerHTML={{ __html: update.content }}
        />
        
        {update.image_urls && update.image_urls.length > 0 && (
          <div className="mt-4 pt-4 border-t border-border">
             <h4 className="text-sm font-medium text-foreground mb-2">Attached Images</h4>
             <StatusUpdateImageThumbnail images={update.image_urls} />
          </div>
        )}

        {update.requested_action && (
          <div className={`mt-4 p-3 rounded-md border flex items-start ${update.requested_action === 'approve' ? 'bg-emerald-50 border-emerald-200 text-emerald-800' : 'bg-destructive/10 border-destructive/20 text-destructive'}`}>
            <AlertCircle className="w-4 h-4 mr-2 mt-0.5 flex-shrink-0" />
            <div className="text-sm">
              <span className="font-bold block mb-0.5">Action Requested</span>
              Please {update.requested_action === 'approve' ? 'approve' : 'reject'} this update.
            </div>
          </div>
        )}

        {canManage && update.voting_enabled && (
          <div className="mt-4 p-3 bg-muted/50 rounded-md border border-border">
            <div className="flex items-center justify-between mb-2">
              <span className="text-xs font-semibold text-muted-foreground uppercase tracking-wider">Voting Results</span>
              <span className="text-xs text-muted-foreground">{votes.length} votes total</span>
            </div>
            <div className="flex gap-2">
              <div className="flex-1 bg-emerald-100 text-emerald-700 px-2 py-1 rounded text-xs font-medium flex items-center justify-center">
                <ThumbsUp className="w-3 h-3 mr-1" /> {approveVotes}
              </div>
              <div className="flex-1 bg-destructive/10 text-destructive px-2 py-1 rounded text-xs font-medium flex items-center justify-center">
                <ThumbsDown className="w-3 h-3 mr-1" /> {rejectVotes}
              </div>
            </div>
          </div>
        )}

        {!canManage && update.voting_enabled && (
          <div className="mt-4 pt-2 border-t border-border">
            {userVote ? (
              <div className={`text-center p-2 rounded text-sm font-medium ${userVote.vote === 'approve' ? 'bg-emerald-50 text-emerald-700' : 'bg-destructive/10 text-destructive'}`}>
                You voted: {userVote.vote.charAt(0).toUpperCase() + userVote.vote.slice(1)}
              </div>
            ) : (
              <div className="flex space-x-2">
                <Button 
                  size="sm" 
                  className="flex-1 bg-emerald-600 hover:bg-emerald-700 text-white"
                  onClick={() => handleVote('approve')}
                  disabled={actionLoading}
                >
                  <ThumbsUp className="w-4 h-4 mr-2" /> Vote Yes
                </Button>
                <Button 
                  size="sm" 
                  variant="destructive"
                  className="flex-1"
                  onClick={() => handleVote('reject')}
                  disabled={actionLoading}
                >
                  <ThumbsDown className="w-4 h-4 mr-2" /> Vote No
                </Button>
              </div>
            )}
          </div>
        )}
      </div>
      
      <div className="bg-muted/50 px-4 md:px-5 py-3 border-t border-border flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 text-sm text-muted-foreground">
        <div className="flex flex-wrap items-center gap-4">
          <div className="flex items-center space-x-2">
            <User className="w-4 h-4 flex-shrink-0" />
            <span className="truncate max-w-[150px]">{update.profiles?.full_name || 'System'}</span>
          </div>
          <div className="flex items-center space-x-2">
            <Calendar className="w-4 h-4 flex-shrink-0" />
            <span>{formatDate(update.created_at)}</span>
          </div>
        </div>
        <div className="flex items-center space-x-2 self-end sm:self-auto">
          {canManage && (
             <Button 
                variant="ghost" 
                size="sm" 
                className={`h-8 px-2 ${update.voting_enabled ? 'text-amber-600 hover:bg-amber-50' : 'text-muted-foreground hover:bg-muted'}`}
                onClick={handleToggleVoting}
                disabled={actionLoading}
              >
                <Vote className="w-4 h-4 mr-2" />
                <span className="hidden sm:inline">{update.voting_enabled ? 'Disable Voting' : 'Enable Voting'}</span>
                <span className="sm:hidden">{update.voting_enabled ? 'Disable' : 'Enable'}</span>
              </Button>
          )}
          <Button 
            variant="ghost" 
            size="sm" 
            onClick={handleToggleComments}
            className={`px-2 transition-colors ${showComments ? 'bg-primary/10 text-primary' : 'text-primary hover:text-primary/80 hover:bg-primary/5'}`}
          >
            <MessageSquare className="w-4 h-4 mr-2" />
            <span>Comments</span>
          </Button>
        </div>
      </div>

      <AnimatePresence>
        {showComments && (
          <motion.div
            initial={{ height: 0, opacity: 0 }}
            animate={{ height: 'auto', opacity: 1 }}
            exit={{ height: 0, opacity: 0 }}
            className="bg-muted/50 border-t border-border overflow-hidden"
          >
            <div className="p-4 md:p-5 space-y-4">
              {loadingComments ? (
                <div className="text-center py-4 text-sm text-muted-foreground">Loading comments...</div>
              ) : comments.length === 0 ? (
                <div className="text-center py-4 text-sm text-muted-foreground">No comments yet. Be the first to comment!</div>
              ) : (
                <div className="space-y-3 max-h-60 overflow-y-auto pr-2">
                  {comments.map((comment) => (
                    <div key={comment.id} className="bg-card p-3 rounded-lg border border-border shadow-sm">
                      <div className="flex justify-between items-start mb-1">
                        <span className="text-xs font-semibold text-primary">{comment.profiles?.email}</span>
                        <span className="text-xs text-muted-foreground">{formatDate(comment.created_at)}</span>
                      </div>
                      <p className="text-sm text-foreground break-words">{comment.content}</p>
                    </div>
                  ))}
                </div>
              )}
              
              <form onSubmit={handleSubmitComment} className="flex gap-2 mt-4">
                <input
                  type="text"
                  value={newComment}
                  onChange={(e) => setNewComment(e.target.value)}
                  placeholder="Write a comment..."
                  className="flex-1 px-3 py-2 text-sm border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring"
                />
                <Button 
                  type="submit" 
                  size="sm" 
                  disabled={submittingComment || !newComment.trim()}
                >
                  {submittingComment ? '...' : <Send className="w-4 h-4" />}
                </Button>
              </form>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </motion.div>
  );
}

export default StatusUpdateCard;
