'use client';

import React, { useState, useMemo } from 'react';
import { X, MessageCircle, Clock, Users, AlertCircle, CheckCircle, Eye, Plus, Filter } from 'lucide-react';
import { useSidebarStore } from '@/stores/sidebar-store';
import useFlowStore, { useFlowStoreActions } from '@/stores/flow-store';

interface CommentData {
  id: string;
  title: string;
  status: 'Open' | 'In Progress' | 'Resolved' | 'Closed';
  priority: 'Low' | 'Medium' | 'High' | 'Critical';
  category: 'Question' | 'Suggestion' | 'Issue' | 'Approval' | 'General';
  comments: Array<{
    id: string;
    author: string;
    content: string;
    timestamp: string;
    parentId?: string;
    type?: 'user' | 'system';
  }>;
  createdAt: string;
  updatedAt: string;
}

function classNames(...classes: any) {
  return classes.filter(Boolean).join(' ');
}

const FeedbackPanel = () => {
  const { showFeedbackPanel, setFeedbackPanelOpen } = useSidebarStore();
  const { nodes } = useFlowStore();
  const { addNode } = useFlowStoreActions();
  const [selectedThreadId, setSelectedThreadId] = useState<string | null>(null);
  const [selectedPriorities, setSelectedPriorities] = useState<Set<string>>(new Set(['Low', 'Medium', 'High', 'Critical']));
  const [selectedCategories, setSelectedCategories] = useState<Set<string>>(new Set(['Question', 'Suggestion', 'Issue', 'Approval', 'General']));
  const [showFilters, setShowFilters] = useState(false);

  // Extract and sort comment threads
  const commentThreads = useMemo(() => {
    const threads = nodes
      .filter(node => node.type === 'comment')
      .map(node => {
        const data = node.data as CommentData;
        return {
          nodeId: node.id,
          id: data?.id || node.id,
          title: data?.title || 'Untitled Thread',
          status: (data?.status || 'Open') as 'Open' | 'In Progress' | 'Resolved' | 'Closed',
          priority: (data?.priority || 'Medium') as 'Low' | 'Medium' | 'High' | 'Critical',
          category: (data?.category || 'General') as 'Question' | 'Suggestion' | 'Issue' | 'Approval' | 'General',
          comments: data?.comments || [],
          createdAt: data?.createdAt || new Date().toISOString(),
          updatedAt: data?.updatedAt || new Date().toISOString()
        };
      })
      .filter(thread => 
        selectedPriorities.has(thread.priority) && 
        selectedCategories.has(thread.category)
      )
      .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
    
    return threads;
  }, [nodes, selectedPriorities, selectedCategories]);

  const statusColors = {
    Open: 'bg-blue-100 text-blue-800 border-blue-300',
    'In Progress': 'bg-yellow-100 text-yellow-800 border-yellow-300',
    Resolved: 'bg-green-100 text-green-800 border-green-300',
    Closed: 'bg-gray-100 text-gray-600 border-gray-300'
  };

  const priorityColors = {
    Low: 'text-gray-600',
    Medium: 'text-blue-700',
    High: 'text-orange-700',
    Critical: 'text-red-700'
  };

  const categoryIcons = {
    Question: '❓',
    Suggestion: '💡', 
    Issue: '⚠️',
    Approval: '✅',
    General: '💬'
  };

  const statusIcons = {
    Open: AlertCircle,
    'In Progress': Clock,
    Resolved: CheckCircle,
    Closed: Eye
  };

  const formatTimeAgo = (timestamp: string) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
    const diffDays = Math.floor(diffHours / 24);

    if (diffDays > 0) return `${diffDays}d ago`;
    if (diffHours > 0) return `${diffHours}h ago`;
    return 'Just now';
  };

  const handleThreadClick = (threadId: string) => {
    // Find the corresponding node and zoom to it
    const node = nodes.find(n => n.id === threadId);
    if (node) {
      setSelectedThreadId(threadId);
      
      // Get ReactFlow instance from the store
      const { reactFlowInstance } = useFlowStore.getState();
      
      if (reactFlowInstance) {
        // Zoom to the specific node with some padding
        reactFlowInstance.fitView({
          nodes: [{ id: threadId }],
          duration: 800, // Smooth animation
          padding: 0.3, // 30% padding around the node
        });
      }
    }
  };

  const togglePriorityFilter = (priority: string) => {
    const newSelected = new Set(selectedPriorities);
    if (newSelected.has(priority)) {
      newSelected.delete(priority);
    } else {
      newSelected.add(priority);
    }
    setSelectedPriorities(newSelected);
  };

  const toggleCategoryFilter = (category: string) => {
    const newSelected = new Set(selectedCategories);
    if (newSelected.has(category)) {
      newSelected.delete(category);
    } else {
      newSelected.add(category);
    }
    setSelectedCategories(newSelected);
  };

  const handleCreateNewThread = () => {
    const newThreadId = `comment-thread-${Date.now()}`;
    const newThread = {
      id: newThreadId,
      type: 'comment',
      position: { x: 100, y: 100 },
      data: {
        id: newThreadId,
        title: 'New Discussion',
        status: 'Open' as const,
        priority: 'Medium' as const,
        category: 'General' as const,
        comments: [],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
    };
    
    addNode(newThread);
    setSelectedThreadId(newThreadId);
  };

  if (!showFeedbackPanel) return null;

  return (
    <div className="fixed right-0 top-0 h-full w-80 bg-white border-l border-gray-200 shadow-lg z-40 flex flex-col">
      {/* Header */}
      <div className="p-4 border-b border-gray-200 flex-shrink-0">
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center">
            <MessageCircle className="w-5 h-5 text-orange-600 mr-2" />
            <h2 className="text-lg font-semibold text-gray-900">Feedback</h2>
          </div>
          <button
            onClick={() => setFeedbackPanelOpen(false)}
            className="text-gray-400 hover:text-gray-600 p-1 rounded"
          >
            <X className="w-5 h-5" />
          </button>
        </div>
        
        {/* Action buttons */}
        <div className="flex items-center justify-between mb-3">
          <button
            onClick={handleCreateNewThread}
            className="flex items-center px-3 py-1.5 bg-orange-600 text-white rounded text-sm hover:bg-orange-700 transition-colors"
          >
            <Plus className="w-4 h-4 mr-1" />
            New Thread
          </button>
          <button
            onClick={() => setShowFilters(!showFilters)}
            className={`flex items-center px-3 py-1.5 rounded text-sm transition-colors ${
              showFilters ? 'bg-gray-200 text-gray-700' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }`}
          >
            <Filter className="w-4 h-4 mr-1" />
            Filter
          </button>
        </div>

        {/* Filter controls */}
        {showFilters && (
          <div className="mb-3 p-3 bg-gray-50 rounded-lg space-y-3">
            {/* Priority filters */}
            <div>
              <h4 className="text-xs font-medium text-gray-700 mb-2">Priority</h4>
              <div className="flex flex-wrap gap-2">
                {['Low', 'Medium', 'High', 'Critical'].map(priority => (
                  <button
                    key={priority}
                    onClick={() => togglePriorityFilter(priority)}
                    className={`px-2 py-1 rounded text-xs font-medium transition-colors ${
                      selectedPriorities.has(priority)
                        ? `${priorityColors[priority as keyof typeof priorityColors]} border`
                        : 'bg-white text-gray-500 border border-gray-300 hover:bg-gray-50'
                    }`}
                  >
                    {priority}
                  </button>
                ))}
              </div>
            </div>
            
            {/* Category filters */}
            <div>
              <h4 className="text-xs font-medium text-gray-700 mb-2">Category</h4>
              <div className="flex flex-wrap gap-2">
                {['Question', 'Suggestion', 'Issue', 'Approval', 'General'].map(category => (
                  <button
                    key={category}
                    onClick={() => toggleCategoryFilter(category)}
                    className={`flex items-center space-x-1 px-2 py-1 rounded text-xs font-medium transition-colors ${
                      selectedCategories.has(category)
                        ? 'bg-blue-100 text-blue-700 border border-blue-300'
                        : 'bg-white text-gray-500 border border-gray-300 hover:bg-gray-50'
                    }`}
                  >
                    <span>{categoryIcons[category as keyof typeof categoryIcons]}</span>
                    <span>{category}</span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        )}
        
        <p className="text-sm text-gray-600">
          {commentThreads.length} {commentThreads.length === 1 ? 'thread' : 'threads'}
          {(selectedPriorities.size < 4 || selectedCategories.size < 5) && (
            <span className="text-gray-500"> (filtered)</span>
          )}
        </p>
      </div>

      {/* Thread List */}
      <div className="flex-1 overflow-y-auto">
        {commentThreads.length === 0 ? (
          <div className="p-6 text-center">
            <MessageCircle className="w-12 h-12 mx-auto text-gray-300 mb-3" />
            <p className="text-gray-500 text-sm">No feedback threads yet</p>
            <p className="text-gray-400 text-xs mt-1">
              Add comment threads to your design to start collecting feedback
            </p>
          </div>
        ) : (
          <div className="p-2">
            {commentThreads.map((thread) => {
              const StatusIcon = statusIcons[thread.status] || AlertCircle;
              const isSelected = selectedThreadId === thread.nodeId;
              
              return (
                <div
                  key={thread.nodeId}
                  onClick={() => handleThreadClick(thread.nodeId)}
                  className={classNames(
                    "p-3 mb-2 rounded-lg border cursor-pointer transition-all hover:shadow-md",
                    isSelected 
                      ? "border-orange-300 bg-orange-50 shadow-sm" 
                      : "border-gray-200 bg-white hover:border-gray-300"
                  )}
                >
                  {/* Thread Header */}
                  <div className="flex items-start justify-between mb-2">
                    <div className="flex items-start flex-1 min-w-0">
                      <span className="text-sm mr-2 flex-shrink-0">
                        {categoryIcons[thread.category]}
                      </span>
                      <div className="min-w-0 flex-1">
                        <h3 className="text-sm font-semibold text-gray-900 truncate">
                          {thread.title}
                        </h3>
                        <p className="text-xs text-gray-500">
                          {thread.category} • {formatTimeAgo(thread.createdAt)}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-1 ml-2 flex-shrink-0">
                      {thread.comments.length > 0 && (
                        <span className="bg-gray-100 text-gray-600 px-2 py-0.5 rounded-full text-xs">
                          {thread.comments.length}
                        </span>
                      )}
                    </div>
                  </div>


                  {/* Thread Footer */}
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <span className={classNames(
                        "text-xs font-medium",
                        priorityColors[thread.priority]
                      )}>
                        {thread.priority}
                      </span>
                      <StatusIcon className="w-3 h-3 text-gray-400" />
                    </div>
                    <span className={classNames(
                      "px-2 py-0.5 rounded text-xs font-medium border",
                      statusColors[thread.status]
                    )}>
                      {thread.status}
                    </span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer Stats */}
      {commentThreads.length > 0 && (
        <div className="p-4 border-t border-gray-200 bg-gray-50 flex-shrink-0">
          <div className="grid grid-cols-2 gap-4 text-center">
            <div>
              <div className="text-lg font-semibold text-orange-600">
                {commentThreads.filter(t => t.status === 'Open' || t.status === 'In Progress').length}
              </div>
              <div className="text-xs text-gray-600">Active</div>
            </div>
            <div>
              <div className="text-lg font-semibold text-green-600">
                {commentThreads.filter(t => t.status === 'Resolved').length}
              </div>
              <div className="text-xs text-gray-600">Resolved</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default FeedbackPanel;