import React, { useState, useEffect, useRef } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Textarea } from '@/components/ui/textarea';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Download, MessageSquare, Send, CheckCircle, XCircle, Clock, Vote, PenTool, FileText, Paperclip, ShieldAlert, FileText as SummaryIcon } from 'lucide-react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/contexts/AuthContext';
import { useToast } from '@/hooks/use-toast';
import { format } from 'date-fns';
import { useCommentCount } from '@/hooks/useCommentCount';

function ARCDetailsDialog({ open, onOpenChange, application, onUpdate }) {
  const { user, isBoardMember, isAdmin } = useAuth();
  const { toast } = useToast();
  const [comments, setComments] = useState([]);
  const [newComment, setNewComment] = useState('');
  const [commentLoading, setCommentLoading] = useState(false);
  const [voteLoading, setVoteLoading] = useState(false);
  const [statusUpdating, setStatusUpdating] = useState(false);
  
  const { count: commentCount, loading: countLoading } = useCommentCount(application?.id, 'arc_application');
  
  const scrollRef = useRef(null);

  const arcFiles = application?.arc_files || [];

  useEffect(() => {
    if (open && application) {
      fetchComments();
    }
  }, [open, application]);

  const fetchComments = async () => {
    if (!application?.id) return;
    
    const { data, error } = await supabase
      .from('arc_comments')
      .select('*')
      .eq('application_id', application.id)
      .order('created_at', { ascending: true });

    if (!error) {
      setComments(data || []);
      setTimeout(() => {
         if (scrollRef.current) {
             scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
         }
      }, 100);
    }
  };

  const handlePostComment = async (e) => {
    e.preventDefault();
    if (!newComment.trim()) return;
    if (!user) {
        toast({ variant: "destructive", title: "Error", description: "You must be logged in to comment." });
        return;
    }

    setCommentLoading(true);
    const { error } = await supabase.from('arc_comments').insert([{
      application_id: application.id,
      user_id: user.id,
      content: newComment
    }]);

    if (!error) {
      setNewComment('');
      fetchComments();
    } else {
      toast({
        variant: "destructive",
        title: "Error posting comment",
        description: error.message
      });
    }
    setCommentLoading(false);
  };

  const handleStatusUpdate = async (newStatus) => {
    if (!application?.id) return;
    setStatusUpdating(true);
    try {
        const { error } = await supabase
            .from('arc_applications')
            .update({ status: newStatus })
            .eq('id', application.id);

        if (error) throw error;

        toast({ title: "Status Updated", description: `Application status changed to ${newStatus}.` });
        if (onUpdate) onUpdate(); 
    } catch (err) {
        console.error(err);
        toast({ variant: "destructive", title: "Error", description: "Failed to update status." });
    } finally {
        setStatusUpdating(false);
    }
  };

  const getStatusBadge = (status) => {
    switch(status) {
        case 'approved': return <Badge className="bg-green-600">Approved</Badge>;
        case 'rejected': return <Badge className="bg-red-600">Rejected</Badge>;
        default: return <Badge variant="outline" className="text-yellow-600 border-yellow-600 bg-yellow-50">Pending</Badge>;
    }
  };

  if (!application) return null;

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[900px] h-[90vh] flex flex-col p-0 overflow-hidden">
        <DialogHeader className="px-6 py-4 border-b">
          <div className="flex flex-col sm:flex-row justify-between items-start gap-4">
            <div>
              <DialogTitle className="text-xl font-bold">{application.title}</DialogTitle>
              <div className="flex items-center gap-2 mt-2">
                {getStatusBadge(application.status)}
                <span className="text-sm text-muted-foreground">
                  {application.associations?.name}
                </span>
                {!countLoading && (
                  <Badge variant="outline" className="ml-2 font-normal">
                    <MessageSquare className="w-3 h-3 mr-1" />
                    Comments ({commentCount})
                  </Badge>
                )}
              </div>
            </div>
          </div>
        </DialogHeader>
        
        <div className="flex-1 overflow-hidden flex flex-col md:flex-row">
          {/* Left Side: Details */}
          <div className="flex-1 overflow-y-auto p-6 space-y-6">
            
            {/* Admin Status Controls */}
            {isAdmin && (
              <div className="p-4 rounded-lg border border-primary/20 shadow-sm">
                <h3 className="font-semibold mb-2 flex items-center text-sm uppercase tracking-wide">
                  <ShieldAlert className="w-4 h-4 mr-2" /> Admin Actions
                </h3>
                <p className="text-sm text-muted-foreground mb-4">
                  Review the application and cast the final decision.
                </p>
                <div className="flex flex-wrap gap-2">
                  <Button 
                    size="sm"
                    className="bg-green-600 hover:bg-green-700 text-white"
                    onClick={() => handleStatusUpdate('approved')}
                    disabled={application.status === 'approved' || statusUpdating}
                  >
                    <CheckCircle className="w-4 h-4 mr-2" />
                    Approve Application
                  </Button>
                  <Button 
                    size="sm"
                    variant="destructive"
                    onClick={() => handleStatusUpdate('rejected')}
                    disabled={application.status === 'rejected' || statusUpdating}
                  >
                    <XCircle className="w-4 h-4 mr-2" />
                    Reject Application
                  </Button>
                  {application.status !== 'submitted' && (
                    <Button 
                      size="sm"
                      variant="outline"
                      onClick={() => handleStatusUpdate('submitted')}
                      disabled={statusUpdating}
                    >
                      Reset to Pending
                    </Button>
                  )}
                </div>
              </div>
            )}

            <div className="p-4 rounded-lg border shadow-sm">
              <h3 className="font-semibold mb-2">Description</h3>
              <p className="text-muted-foreground whitespace-pre-wrap">{application.description}</p>
            </div>

            {/* Attachments Section */}
            <div className="p-4 rounded-lg border shadow-sm">
              <h3 className="font-semibold mb-3 flex items-center">
                <Paperclip className="w-4 h-4 mr-2" /> 
                Attachments ({arcFiles.length})
              </h3>
              {arcFiles.length > 0 ? (
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                  {arcFiles.map(file => (
                    <a 
                      key={file.id}
                      href={file.file_url} 
                      target="_blank" 
                      rel="noopener noreferrer"
                      className="flex items-center p-3 rounded border hover:bg-muted transition-colors group"
                    >
                      <FileText className="w-5 h-5 text-primary mr-3" />
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate group-hover:text-primary">
                          {file.file_name}
                        </p>
                        <p className="text-xs text-muted-foreground">
                          {format(new Date(file.created_at), 'MMM d, yyyy')}
                        </p>
                      </div>
                      <Download className="w-4 h-4 text-muted-foreground group-hover:text-primary" />
                    </a>
                  ))}
                </div>
              ) : (
                <div className="text-center py-4 bg-muted/30 rounded border border-dashed">
                  <p className="text-sm text-muted-foreground">No attachments uploaded.</p>
                </div>
              )}
            </div>
          </div>

          {/* Right Side: Comments */}
          <div className="w-full md:w-[350px] flex flex-col border-l">
            <div className="p-4 border-b flex justify-between items-center">
              <h3 className="font-semibold flex items-center">
                <MessageSquare className="w-4 h-4 mr-2" /> Discussion
              </h3>
              {!countLoading && (
                <Badge variant="secondary" className="text-xs font-normal">
                  {commentCount}
                </Badge>
              )}
            </div>
            
            <div className="flex-1 overflow-y-auto p-4 space-y-4" ref={scrollRef}>
              {comments.length === 0 ? (
                <div className="text-center py-8 text-muted-foreground text-sm">
                  No comments yet. Start the discussion!
                </div>
              ) : (
                comments.map((comment) => (
                  <div key={comment.id} className={`flex flex-col ${comment.user_id === user?.id ? 'items-end' : 'items-start'}`}>
                    <div className={`max-w-[85%] rounded-lg p-3 text-sm ${
                      comment.user_id === user?.id 
                      ? 'bg-primary text-primary-foreground' 
                      : 'bg-muted border'
                    }`}>
                      <p>{comment.content}</p>
                    </div>
                    <span className="text-[10px] text-muted-foreground mt-1 px-1">
                      {format(new Date(comment.created_at), 'MMM d, h:mm a')}
                    </span>
                  </div>
                ))
              )}
            </div>

            <div className="p-4 border-t">
              <form onSubmit={handlePostComment} className="flex gap-2">
                <Textarea 
                  value={newComment}
                  onChange={(e) => setNewComment(e.target.value)}
                  placeholder="Type a comment..."
                  className="min-h-[40px] max-h-[100px] resize-none"
                  onKeyDown={(e) => {
                    if (e.key === 'Enter' && !e.shiftKey) {
                      e.preventDefault();
                      handlePostComment(e);
                    }
                  }}
                />
                <Button type="submit" size="icon" disabled={commentLoading || !newComment.trim()}>
                  <Send className="w-4 h-4" />
                </Button>
              </form>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

export default ARCDetailsDialog;
