import React, { useState, useRef, useEffect } from "react";
import { base44 } from "@/api/base44Client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Badge } from "@/components/ui/badge";
import { Avatar } from "@/components/ui/avatar";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";

import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs";
import { Calendar, Paperclip, Send, Upload, FileText, Download, AtSign, Smile, Plus, Home, Activity, Mail, Clock, Zap, PauseCircle, CheckCircle } from "lucide-react";
import { format } from "date-fns";
import { useToast } from "@/components/ui/use-toast";

const priorityConfig = {
  high: { bg: "bg-blue-100", text: "text-blue-700", label: "High" },
  normal: { bg: "bg-teal-100", text: "text-teal-700", label: "Normal" },
  low: { bg: "bg-amber-100", text: "text-amber-700", label: "Low" }
};

export default function TaskDetailModal({ task, open, onClose }) {
  const { toast } = useToast();
  const queryClient = useQueryClient();
  const [comment, setComment] = useState("");
  const [uploading, setUploading] = useState(false);
  const [status, setStatus] = useState(task?.status || "pending");
  const [activeTab, setActiveTab] = useState("updates");
  const [emailNotification, setEmailNotification] = useState(false);
  const fileInputRef = useRef(null);

  // Auto-calculate progress based on activity
  const calculateProgress = () => {
    if (!task) return 0;
    
    let progressScore = 0;
    
    // Status contributes to progress
    if (task.status === "completed") return 100;
    if (task.status === "in_progress") progressScore += 40;
    if (task.status === "on_hold") progressScore += 20;
    
    // Comments/updates show activity
    if (task.comment_count > 0) progressScore += Math.min(task.comment_count * 5, 20);
    
    // Files attached show work done
    if (task.attachment_count > 0) progressScore += Math.min(task.attachment_count * 10, 20);
    
    // Assigned members
    if (task.assigned_members?.length > 0) progressScore += 20;
    
    return Math.min(progressScore, 100);
  };

  const currentProgress = calculateProgress();

  useEffect(() => {
    if (task && currentProgress !== task.progress) {
      updateTaskMutation.mutate({
        id: task.id,
        data: { ...task, progress: currentProgress }
      });
    }
  }, [currentProgress]);

  const { data: user } = useQuery({
    queryKey: ['current-user-task-modal'],
    queryFn: () => base44.auth.me(),
  });

  const { data: comments = [] } = useQuery({
    queryKey: ['task-comments', task?.id],
    queryFn: () => base44.entities.TaskComment.filter({ task_id: task?.id }),
    enabled: !!task?.id,
    initialData: [],
  });

  const addCommentMutation = useMutation({
    mutationFn: (commentData) => base44.entities.TaskComment.create(commentData),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['task-comments', task?.id] });
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      setComment("");
      toast({
        title: "✅ Comment Added",
        description: "Your comment has been posted",
      });
    },
  });

  const updateTaskMutation = useMutation({
    mutationFn: ({ id, data }) => base44.entities.Task.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['tasks'] });
      toast({
        title: "✅ Task Updated",
        description: "Changes saved successfully",
      });
    },
  });

  const handleFileUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      
      const newFile = {
        file_name: file.name,
        file_url: file_url,
        file_size: file.size,
        uploaded_by: user?.full_name || user?.email || "User",
        uploaded_at: new Date().toISOString(),
      };

      const updatedFiles = [...(task.files || []), newFile];
      
      await updateTaskMutation.mutateAsync({
        id: task.id,
        data: {
          ...task,
          files: updatedFiles,
          attachment_count: updatedFiles.length,
        }
      });

      // Add system comment
      await addCommentMutation.mutateAsync({
        task_id: task.id,
        author_id: user?.id,
        author_name: user?.full_name || user?.email || "User",
        author_avatar: user?.profile_picture,
        comment: `Uploaded file: ${file.name}`,
        is_system: true,
      });

      toast({
        title: "✅ File Uploaded",
        description: `${file.name} added successfully`,
      });
    } catch (error) {
      toast({
        title: "❌ Upload Failed",
        description: error.message,
        variant: "destructive",
      });
    } finally {
      setUploading(false);
    }
  };

  const handleStatusChange = async (newStatus) => {
    setStatus(newStatus);
    await updateTaskMutation.mutateAsync({
      id: task.id,
      data: { ...task, status: newStatus }
    });

    // Add system comment
    await addCommentMutation.mutateAsync({
      task_id: task.id,
      author_id: user?.id,
      author_name: "System",
      author_avatar: "",
      comment: `Status changed to ${newStatus.replace('_', ' ')}`,
      is_system: true,
    });
  };

  const handleAddComment = async () => {
    if (!comment.trim()) return;

    await addCommentMutation.mutateAsync({
      task_id: task.id,
      author_id: user?.id,
      author_name: user?.full_name || user?.email || "User",
      author_avatar: user?.profile_picture,
      comment: comment.trim(),
      is_system: false,
    });

    // Update comment count
    await updateTaskMutation.mutateAsync({
      id: task.id,
      data: {
        ...task,
        comment_count: (task.comment_count || 0) + 1,
      }
    });

    // Send email notifications if enabled
    if (emailNotification && task.assigned_members) {
      for (const member of task.assigned_members) {
        try {
          await base44.integrations.Core.SendEmail({
            to: member.member_email || `${member.member_name}@example.com`,
            subject: `New update on task: ${task.task_name}`,
            body: `${user?.full_name || "A team member"} posted an update:\n\n"${comment.trim()}"\n\nView task details in the app.`
          });
        } catch (error) {
          console.error("Failed to send email:", error);
        }
      }
      toast({
        title: "✅ Update Sent",
        description: "Email notifications sent to team members",
      });
    }
  };

  const handleMention = () => {
    const textarea = document.querySelector('textarea');
    if (textarea) {
      const cursorPos = textarea.selectionStart;
      const textBefore = comment.substring(0, cursorPos);
      const textAfter = comment.substring(cursorPos);
      setComment(textBefore + '@' + textAfter);
      setTimeout(() => {
        textarea.focus();
        textarea.setSelectionRange(cursorPos + 1, cursorPos + 1);
      }, 0);
    }
  };

  const handleEmoji = () => {
    const emojis = ['👍', '❤️', '😊', '🎉', '✅', '🔥', '💪', '🚀'];
    const randomEmoji = emojis[Math.floor(Math.random() * emojis.length)];
    setComment(comment + randomEmoji);
  };

  if (!task) return null;

  const priority = priorityConfig[task.priority] || priorityConfig.normal;
  const sortedComments = [...comments].sort((a, b) => 
    new Date(a.created_date) - new Date(b.created_date)
  );

  const getProgressColor = () => {
    if (currentProgress === 100) return "bg-green-500";
    if (currentProgress >= 70) return "bg-blue-500";
    if (currentProgress >= 40) return "bg-amber-500";
    return "bg-slate-400";
  };

  const statusOptions = [
    { value: "pending", label: "Pending", icon: Clock, color: "bg-slate-100 text-slate-700 border-slate-300" },
    { value: "in_progress", label: "In Progress", icon: Zap, color: "bg-blue-100 text-blue-700 border-blue-300" },
    { value: "on_hold", label: "On Hold", icon: PauseCircle, color: "bg-orange-100 text-orange-700 border-orange-300" },
    { value: "completed", label: "Completed", icon: CheckCircle, color: "bg-green-100 text-green-700 border-green-300" },
  ];

  return (
    <Dialog open={open} onOpenChange={onClose}>
      <DialogContent className="max-w-5xl max-h-[90vh] overflow-hidden flex flex-col p-0">
        {/* Header with Task Info */}
        <div className="p-6 pb-4 border-b">
          <div className="flex items-start justify-between mb-4">
            <div className="flex-1">
              <h2 className="text-2xl font-bold text-slate-900 mb-2">{task.task_name}</h2>
              <div className="flex items-center gap-3 flex-wrap">
                <Badge className={`${priority.bg} ${priority.text} text-xs font-semibold px-3 py-1`}>
                  {priority.label} Priority
                </Badge>
                {task.due_date && (
                  <div className="flex items-center gap-1.5 text-sm text-slate-600 bg-slate-100 px-3 py-1 rounded-full">
                    <Calendar className="w-3.5 h-3.5" />
                    {format(new Date(task.due_date), 'MMM d, yyyy')}
                  </div>
                )}
                <div className="flex items-center gap-2">
                  <div className={`h-2 w-24 bg-slate-200 rounded-full overflow-hidden`}>
                    <div className={`h-full ${getProgressColor()} transition-all duration-500`} style={{ width: `${currentProgress}%` }}></div>
                  </div>
                  <span className="text-sm font-semibold text-slate-700">{currentProgress}%</span>
                </div>
              </div>
            </div>
            
            <div className="flex flex-wrap gap-2">
              {statusOptions.map((option) => {
                const IconComponent = option.icon;
                return (
                  <button
                    key={option.value}
                    onClick={() => handleStatusChange(option.value)}
                    className={`flex items-center gap-2 px-4 py-2 rounded-lg border-2 font-semibold text-sm transition-all ${
                      status === option.value
                        ? `${option.color} shadow-md scale-105`
                        : "bg-white text-slate-400 border-slate-200 hover:border-slate-300 hover:text-slate-600"
                    }`}
                  >
                    <IconComponent className="w-4 h-4" />
                    {option.label}
                  </button>
                );
              })}
            </div>
          </div>

          {/* Assigned Members */}
          {task.assigned_members && task.assigned_members.length > 0 && (
            <div className="flex items-center gap-3">
              <span className="text-xs font-semibold text-slate-500">ASSIGNED:</span>
              <div className="flex -space-x-2">
                {task.assigned_members.slice(0, 5).map((member, idx) => (
                  <Avatar key={idx} className="w-8 h-8 border-2 border-white">
                    <img 
                      src={member.avatar_url || `https://i.pravatar.cc/150?u=${encodeURIComponent(member.member_name)}`}
                      alt={member.member_name}
                      title={member.member_name}
                      className="w-full h-full object-cover"
                    />
                  </Avatar>
                ))}
                {task.assigned_members.length > 5 && (
                  <div className="w-8 h-8 rounded-full bg-slate-200 border-2 border-white flex items-center justify-center text-xs font-bold text-slate-600">
                    +{task.assigned_members.length - 5}
                  </div>
                )}
              </div>
            </div>
          )}
        </div>

        {/* Tabs */}
        <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col overflow-hidden">
          <TabsList className="w-full justify-start rounded-none border-b bg-transparent px-6 h-12">
            <TabsTrigger value="updates" className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none">
              <Home className="w-4 h-4" />
              Updates
            </TabsTrigger>
            <TabsTrigger value="files" className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none">
              <Paperclip className="w-4 h-4" />
              Files ({task.files?.length || 0})
            </TabsTrigger>
            <TabsTrigger value="activity" className="gap-2 data-[state=active]:border-b-2 data-[state=active]:border-[#0A39DF] rounded-none">
              <Activity className="w-4 h-4" />
              Activity Log
            </TabsTrigger>
          </TabsList>

          {/* Updates Tab */}
          <TabsContent value="updates" className="flex-1 overflow-y-auto m-0 p-6 space-y-4">
            <div className="bg-white border-2 border-slate-200 rounded-xl overflow-hidden">
              <div className="p-4 border-b bg-slate-50 flex items-center justify-between">
                <span className="text-sm font-semibold text-slate-600">Write an update</span>
                <Button 
                  variant="ghost" 
                  size="sm" 
                  onClick={() => setEmailNotification(!emailNotification)}
                  className={emailNotification ? "text-[#0A39DF] bg-blue-50" : "text-slate-500 hover:text-[#0A39DF]"}
                >
                  <Mail className="w-4 h-4 mr-2" />
                  {emailNotification ? "Email enabled ✓" : "Update via email"}
                </Button>
              </div>
              <Textarea
                value={comment}
                onChange={(e) => setComment(e.target.value)}
                placeholder="Write an update and mention others with @"
                rows={4}
                className="border-0 resize-none focus-visible:ring-0 text-base"
              />
              <div className="p-3 bg-slate-50 flex items-center justify-between border-t">
                <div className="flex items-center gap-2">
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={handleMention}
                    className="text-slate-500 hover:text-[#0A39DF]"
                    title="Mention someone"
                  >
                    <AtSign className="w-4 h-4" />
                  </Button>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={() => fileInputRef.current?.click()}
                    disabled={uploading}
                    className="text-slate-500 hover:text-[#0A39DF]"
                    title="Attach file"
                  >
                    <Paperclip className="w-4 h-4" />
                  </Button>
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={handleEmoji}
                    className="text-slate-500 hover:text-[#0A39DF]"
                    title="Add emoji"
                  >
                    <Smile className="w-4 h-4" />
                  </Button>
                  <input ref={fileInputRef} type="file" onChange={handleFileUpload} className="hidden" />
                </div>
                <Button
                  onClick={handleAddComment}
                  disabled={!comment.trim() || addCommentMutation.isPending}
                  className="bg-[#0A39DF] hover:bg-blue-700"
                >
                  <Send className="w-4 h-4 mr-2" />
                  {addCommentMutation.isPending ? "Posting..." : "Post Update"}
                </Button>
              </div>
            </div>

            {/* Comments Feed */}
            <div className="space-y-3">
              {sortedComments.length === 0 ? (
                <div className="text-center py-12 text-slate-400">
                  <Home className="w-16 h-16 mx-auto mb-3 opacity-20" />
                  <p className="text-sm">No updates yet. Be the first to post!</p>
                </div>
              ) : (
                sortedComments.map((commentItem) => (
                  <div key={commentItem.id} className="bg-white border border-slate-200 rounded-xl p-4 hover:shadow-md transition-shadow">
                    <div className="flex gap-3">
                      <Avatar className="w-10 h-10 flex-shrink-0">
                        <img 
                          src={commentItem.author_avatar || `https://i.pravatar.cc/150?u=${encodeURIComponent(commentItem.author_name)}`}
                          alt={commentItem.author_name}
                          className="w-full h-full object-cover"
                        />
                      </Avatar>
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-2">
                          <span className="font-bold text-slate-900">{commentItem.author_name}</span>
                          {commentItem.is_system && (
                            <Badge variant="outline" className="text-xs">System</Badge>
                          )}
                          <span className="text-xs text-slate-400">•</span>
                          <span className="text-xs text-slate-500">
                            {format(new Date(commentItem.created_date), 'MMM d, h:mm a')}
                          </span>
                        </div>
                        <p className="text-slate-700 leading-relaxed">{commentItem.comment}</p>
                      </div>
                    </div>
                  </div>
                ))
              )}
            </div>
          </TabsContent>

          {/* Files Tab */}
          <TabsContent value="files" className="flex-1 overflow-y-auto m-0 p-6">
            <div className="mb-4">
              <Button
                onClick={() => fileInputRef.current?.click()}
                disabled={uploading}
                className="bg-[#0A39DF] hover:bg-blue-700"
              >
                <Upload className="w-4 h-4 mr-2" />
                {uploading ? "Uploading..." : "Upload File"}
              </Button>
            </div>

            {task.files && task.files.length > 0 ? (
              <div className="grid grid-cols-1 gap-3">
                {task.files.map((file, idx) => (
                  <div key={idx} className="flex items-center justify-between p-4 bg-white border-2 border-slate-200 rounded-xl hover:shadow-md transition-shadow">
                    <div className="flex items-center gap-4 flex-1 min-w-0">
                      <div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center flex-shrink-0">
                        <FileText className="w-6 h-6 text-blue-600" />
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="font-semibold text-slate-900 truncate">{file.file_name}</p>
                        <div className="flex items-center gap-2 text-xs text-slate-500 mt-1">
                          <span>{(file.file_size / 1024).toFixed(1)} KB</span>
                          <span>•</span>
                          <span>{file.uploaded_by}</span>
                          <span>•</span>
                          <span>{format(new Date(file.uploaded_at), 'MMM d, h:mm a')}</span>
                        </div>
                      </div>
                    </div>
                    <a href={file.file_url} target="_blank" rel="noopener noreferrer">
                      <Button size="sm" variant="outline" className="border-blue-200 text-blue-600 hover:bg-blue-50">
                        <Download className="w-4 h-4 mr-2" />
                        Download
                      </Button>
                    </a>
                  </div>
                ))}
              </div>
            ) : (
              <div className="text-center py-16 border-2 border-dashed border-slate-200 rounded-xl">
                <Paperclip className="w-16 h-16 mx-auto mb-3 text-slate-300" />
                <p className="text-slate-500 font-medium mb-2">No files attached yet</p>
                <p className="text-sm text-slate-400">Upload files to share with your team</p>
              </div>
            )}
          </TabsContent>

          {/* Activity Log Tab */}
          <TabsContent value="activity" className="flex-1 overflow-y-auto m-0 p-6">
            <div className="space-y-2">
              {sortedComments.filter(c => c.is_system).length === 0 ? (
                <div className="text-center py-16 text-slate-400">
                  <Activity className="w-16 h-16 mx-auto mb-3 opacity-20" />
                  <p className="text-sm">No activity logged yet</p>
                </div>
              ) : (
                <div className="relative">
                  <div className="absolute left-4 top-0 bottom-0 w-0.5 bg-slate-200"></div>
                  {sortedComments.filter(c => c.is_system).map((activity) => (
                    <div key={activity.id} className="relative pl-10 pb-6">
                      <div className="absolute left-2.5 w-3 h-3 bg-[#0A39DF] rounded-full border-2 border-white"></div>
                      <div className="bg-white border border-slate-200 rounded-lg p-3">
                        <p className="text-sm text-slate-700">{activity.comment}</p>
                        <p className="text-xs text-slate-400 mt-1">
                          {format(new Date(activity.created_date), 'MMM d, yyyy • h:mm a')}
                        </p>
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          </TabsContent>
        </Tabs>
      </DialogContent>
    </Dialog>
  );
}