import React, { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  fetchPosts,
  generatePost,
  createPost,
  publishPostDirect,
  deletePost,
  updatePostContent,
  clearError
} from '../store/reducers/postsSlice';
import { fetchAccounts } from '../store/reducers/accountsSlice';

const Posts = () => {
  const dispatch = useDispatch();
  const { items: posts, loading, error } = useSelector(state => state.posts);
  const { items: accounts } = useSelector(state => state.accounts);
  
  const [selectedAccount, setSelectedAccount] = useState('');
  const [postContent, setPostContent] = useState('');
  const [isGenerating, setIsGenerating] = useState(false);
  const [isCreating, setIsCreating] = useState(false);
  
  useEffect(() => {
    dispatch(fetchPosts());
    dispatch(fetchAccounts());
    dispatch(clearError());
  }, [dispatch]);
  
  const handleGeneratePost = async () => {
    setIsGenerating(true);
    
    try {
      const result = await dispatch(generatePost()).unwrap();
      
      // Handle case where content might be a list
      let content = result.content || 'Generated content will appear here...';
      
      // If content is an array, take the first element
      if (Array.isArray(content)) {
        content = content[0] || 'Generated content will appear here...';
      }
      
      setPostContent(content);
    } catch (err) {
      console.error('Failed to generate post:', err);
      // Show a user-friendly error message
      dispatch(clearError());
      // You can dispatch a new action to set a specific error message
      // or use a local state variable to display the error
    } finally {
      setIsGenerating(false);
    }
  };
  
  const handleCreatePost = async (e) => {
    e.preventDefault();
    
    if (!selectedAccount || !postContent.trim()) {
      console.log('📝 [Posts] Missing required fields:', { selectedAccount, postContentLength: postContent.trim().length });
      return;
    }
    
    console.log('📝 [Posts] Publishing post directly to LinkedIn and saving to database:', { selectedAccount, postContentLength: postContent.length });
    
    setIsCreating(true);
    
    try {
      // First, publish directly to LinkedIn
      console.log('📝 [Posts] Publishing to LinkedIn');
      await dispatch(publishPostDirect({
        social_account_id: selectedAccount,
        text_content: postContent
      })).unwrap();
      
      console.log('📝 [Posts] Published to LinkedIn successfully');
      
      // Then save to database as already published
      console.log('📝 [Posts] Saving post to database as published');
      await dispatch(createPost({
        social_account_id: selectedAccount,
        text_content: postContent,
        is_published: true // Mark as published since we've already published it
      })).unwrap();
      
      console.log('📝 [Posts] Post saved to database');
      
      // Reset form
      setSelectedAccount('');
      setPostContent('');
    } catch (err) {
      console.error('📝 [Posts] Failed to publish and save post:', err);
    } finally {
      setIsCreating(false);
    }
  };
  
  const handleDeletePost = async (postId) => {
    try {
      await dispatch(deletePost(postId)).unwrap();
    } catch (err) {
      console.error('Failed to delete post:', err);
    }
  };
  
  const handleContentChange = (content) => {
    setPostContent(content);
  };
  
  // Filter published posts
  const publishedPosts = posts.filter(post => post.is_published);
  
  return (
    <div className="posts-page min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-50 p-3 sm:p-4 lg:p-6">
      <div className="max-w-7xl mx-auto">
        {/* Header Section */}
        <div className="posts-header mb-6 sm:mb-8 lg:mb-10 animate-slide-up">
          <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-3 sm:mb-4 gap-4">
            <div className="flex-1">
              <h1 className="posts-title text-2xl sm:text-3xl lg:text-4xl font-bold bg-gradient-to-r from-gray-900 via-gray-800 to-gray-900 bg-clip-text text-transparent mb-1 sm:mb-2">
                Post Management
              </h1>
              <p className="posts-subtext text-base sm:text-lg text-gray-600 font-medium max-w-2xl sm:max-w-3xl">
                Create and publish your social media posts with intelligent content generation
              </p>
            </div>
            <div className="hidden sm:block lg:block">
              <div className="w-12 h-12 sm:w-16 sm:h-16 bg-gradient-to-br from-gray-900 to-gray-800 rounded-2xl shadow-lg flex items-center justify-center">
                <svg className="w-6 h-6 sm:w-8 sm:h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
              </div>
            </div>
          </div>
          
          {/* Stats Cards */}
          <div className="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mt-6 sm:mt-8">
            <div className="bg-white/80 backdrop-blur-sm rounded-xl p-3 sm:p-4 border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-300">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Total Posts</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900">{posts.length}</p>
                </div>
                <div className="w-8 h-8 sm:w-10 sm:h-10 bg-blue-100 rounded-lg flex items-center justify-center">
                  <svg className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                  </svg>
                </div>
              </div>
            </div>
            
            <div className="bg-white/80 backdrop-blur-sm rounded-xl p-3 sm:p-4 border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-300">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Published</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900">{publishedPosts.length}</p>
                </div>
                <div className="w-8 h-8 sm:w-10 sm:h-10 bg-green-100 rounded-lg flex items-center justify-center">
                  <svg className="w-4 h-4 sm:w-5 sm:h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
              </div>
            </div>
            
            <div className="bg-white/80 backdrop-blur-sm rounded-xl p-3 sm:p-4 border border-gray-200/50 shadow-sm hover:shadow-md transition-all duration-300">
              <div className="flex items-center justify-between">
                <div>
                  <p className="text-xs sm:text-sm font-medium text-gray-600">Accounts</p>
                  <p className="text-lg sm:text-2xl font-bold text-gray-900">{accounts.length}</p>
                </div>
                <div className="w-8 h-8 sm:w-10 sm:h-10 bg-purple-100 rounded-lg flex items-center justify-center">
                  <svg className="w-4 h-4 sm:w-5 sm:h-5 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                  </svg>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        {/* Error Display */}
        {error && (
          <div className="mb-6 sm:mb-8 animate-fade-in">
            <div className="bg-red-50 border border-red-200 rounded-xl p-3 sm:p-4 flex items-start space-x-3">
              <div className="flex-shrink-0">
                <svg className="w-4 h-4 sm:w-5 sm:h-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
                </svg>
              </div>
              <div className="flex-1">
                <p className="text-xs sm:text-sm font-medium text-red-800">{error}</p>
              </div>
            </div>
          </div>
        )}
        
        <div className="posts-content space-y-6 sm:space-y-8">
          {/* Post Creation Section */}
          <div className="post-creation-section bg-white/90 backdrop-blur-sm rounded-2xl p-4 sm:p-6 shadow-lg border border-gray-200/30 hover:shadow-xl transition-all duration-300 animate-slide-up">
            <div className="flex items-center justify-between mb-4 sm:mb-6">
              <h2 className="section-title text-xl sm:text-2xl font-bold text-gray-900 flex items-center space-x-2 sm:space-x-3">
                <div className="w-6 h-6 sm:w-8 sm:h-8 bg-gradient-to-br from-gray-900 to-gray-800 rounded-lg flex items-center justify-center">
                  <svg className="w-3 h-3 sm:w-5 sm:h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                  </svg>
                </div>
                <span className="text-sm sm:text-base">Create New Post</span>
              </h2>
            </div>
            
            <div className="space-y-4 sm:space-y-6">
              {/* AI Generator */}
              <div className="bg-gradient-to-r from-gray-50 to-gray-100 rounded-xl p-4 sm:p-6 border border-gray-200/50">
                <div className="flex items-center justify-between mb-3 sm:mb-4">
                  <h3 className="text-base sm:text-lg font-semibold text-gray-900 flex items-center space-x-2">
                    <svg className="w-4 h-4 sm:w-5 sm:h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
                    </svg>
                    <span className="text-sm sm:text-base">AI Content Generator</span>
                  </h3>
                  <span className="text-xs text-gray-500 bg-gray-200 px-2 py-1 rounded-full">Powered by AI</span>
                </div>
                
                <button
                  className="btn btn-primary generate-button w-full bg-gradient-to-r from-gray-900 to-gray-800 text-white py-2.5 sm:py-3 px-4 sm:px-6 rounded-xl font-semibold hover:from-gray-800 hover:to-gray-900 transition-all duration-300 shadow-lg hover:shadow-xl disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-center space-x-2 touch-manipulation active:scale-95"
                  onClick={handleGeneratePost}
                  disabled={isGenerating}
                  aria-busy={isGenerating}
                >
                  {isGenerating ? (
                    <>
                      <svg className="animate-spin w-4 h-4 sm:w-5 sm:h-5 text-white" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span className="text-xs sm:text-sm">Generating (may take 2-5 minutes)...</span>
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
                      </svg>
                      <span className="text-xs sm:text-sm">Generate Post Content</span>
                    </>
                  )}
                </button>
                {isGenerating && (
                  <p className="text-xs text-gray-500 mt-2 text-center">
                    Please wait while we generate your post. This may take 2-5 minutes.
                  </p>
                )}
              </div>
              
              {/* Content Editor */}
              <div className="space-y-3 sm:space-y-4">
                <label className="block text-xs sm:text-sm font-semibold text-gray-700">Post Content</label>
                <div className="relative">
                  <textarea
                    value={postContent}
                    onChange={(e) => handleContentChange(e.target.value)}
                    placeholder="Click 'Generate Post Content' above to create content with AI, or write your own... (May take 2-5 minutes for AI generation)"
                    className="post-content-textarea w-full px-3 sm:px-4 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-gray-900 focus:border-transparent transition-all duration-300 resize-vertical bg-white/80 backdrop-blur-sm shadow-sm hover:shadow-md touch-manipulation"
                    rows={5}
                    aria-label="Post content"
                  />
                  <div className="absolute bottom-2 sm:bottom-3 right-2 sm:right-3 text-xs text-gray-400">
                    {postContent.length}/280
                  </div>
                </div>
              </div>
              
              {/* Create Post Form */}
              <form onSubmit={handleCreatePost} className="create-post-form grid grid-cols-1 sm:grid-cols-3 gap-3 sm:gap-4">
                <div className="form-field sm:col-span-2">
                  <label className="form-label block text-xs sm:text-sm font-semibold text-gray-700 mb-1 sm:mb-2">Select Account</label>
                  <select
                    value={selectedAccount}
                    onChange={(e) => setSelectedAccount(e.target.value)}
                    className="form-select w-full px-3 sm:px-4 py-2.5 sm:py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-gray-900 focus:border-transparent transition-all duration-300 bg-white/80 backdrop-blur-sm shadow-sm hover:shadow-md touch-manipulation"
                    disabled={isCreating}
                    aria-label="Select social account"
                  >
                    <option value="">Select a social account</option>
                    {accounts.map(account => (
                      <option key={account.id} value={account.id}>
                        {account.account_name} ({account.social_network})
                      </option>
                    ))}
                  </select>
                </div>
                
                <button
                  type="submit"
                  className="btn btn-primary create-button bg-gradient-to-r from-gray-900 to-gray-800 text-white py-2.5 sm:py-3 px-4 sm:px-6 rounded-xl font-semibold hover:from-gray-800 hover:to-gray-900 transition-all duration-300 shadow-lg hover:shadow-xl disabled:opacity-60 disabled:cursor-not-allowed h-fit flex items-center justify-center space-x-2 touch-manipulation active:scale-95"
                  disabled={isCreating || !selectedAccount || !postContent.trim()}
                  aria-busy={isCreating}
                >
                  {isCreating ? (
                    <>
                      <svg className="animate-spin w-4 h-4 sm:w-5 sm:h-5 text-white" fill="none" viewBox="0 0 24 24">
                        <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                        <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                      </svg>
                      <span className="text-xs sm:text-sm">Creating & Publishing...</span>
                    </>
                  ) : (
                    <>
                      <svg className="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                      </svg>
                      <span className="text-xs sm:text-sm">Create and Publish Post</span>
                    </>
                  )}
                </button>
              </form>
            </div>
          </div>
          
          {/* Published Posts Section */}
          <div className="posts-list-section bg-white/90 backdrop-blur-sm rounded-2xl p-4 sm:p-6 shadow-lg border border-gray-200/30 hover:shadow-xl transition-all duration-300 animate-slide-up">
            <div className="flex items-center justify-between mb-4 sm:mb-6">
              <h2 className="section-title text-xl sm:text-2xl font-bold text-gray-900 flex items-center space-x-2 sm:space-x-3">
                <div className="w-6 h-6 sm:w-8 sm:h-8 bg-gradient-to-br from-green-500 to-emerald-600 rounded-lg flex items-center justify-center">
                  <svg className="w-3 h-3 sm:w-5 sm:h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
                <span className="text-sm sm:text-base">Published Posts</span>
              </h2>
              <span className="bg-green-100 text-green-800 text-xs sm:text-sm font-medium px-2 sm:px-3 py-0.5 sm:py-1 rounded-full">
                {publishedPosts.length} posts
              </span>
            </div>
            
            {loading ? (
              <div className="flex items-center justify-center py-8 sm:py-12">
                <div className="animate-pulse">
                  <div className="w-6 h-6 sm:w-8 sm:h-8 bg-gray-300 rounded-full"></div>
                </div>
              </div>
            ) : publishedPosts.length === 0 ? (
              <div className="text-center py-8 sm:py-12">
                <div className="w-12 h-12 sm:w-16 sm:h-16 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-3 sm:mb-4">
                  <svg className="w-6 h-6 sm:w-8 sm:h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                  </svg>
                </div>
                <h3 className="text-base sm:text-lg font-semibold text-gray-900 mb-1 sm:mb-2">No published posts yet</h3>
                <p className="text-xs sm:text-sm text-gray-600">Your published posts will appear here once you publish them.</p>
              </div>
            ) : (
              <div className="posts-list space-y-3 sm:space-y-4">
                {publishedPosts
                  .slice()
                  .sort((a, b) => new Date(b.created_at) - new Date(a.created_at))
                  .map((post, index) => (
                  <div key={post.id} className="post-item group border border-green-200 rounded-xl bg-gradient-to-r from-green-50 to-white hover:from-green-100 hover:to-white transition-all duration-300 hover:shadow-lg animate-fade-in" style={{animationDelay: `${index * 100}ms`}}>
                    <div className="post-content p-4 sm:p-6">
                      <div className="flex items-start justify-between mb-3 sm:mb-4">
                        <div className="flex-1">
                          <p className="post-text text-gray-800 text-base sm:text-lg leading-relaxed mb-3 sm:mb-4">{post.Text_content}</p>
                          <div className="post-meta flex flex-wrap items-center gap-2 sm:gap-4 text-xs sm:text-sm">
                            <span className="post-date text-gray-600 font-medium flex items-center space-x-1">
                              <svg className="w-3 h-3 sm:w-4 sm:h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                              </svg>
                              <span>Created: {new Date(post.created_at).toLocaleDateString()} at {new Date(post.created_at).toLocaleTimeString()}</span>
                            </span>
                            {post.updated_at && post.updated_at !== post.created_at && (
                              <span className="post-updated text-gray-500 flex items-center space-x-1">
                                <svg className="w-3 h-3 sm:w-4 sm:h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                                </svg>
                                <span>Updated: {new Date(post.updated_at).toLocaleDateString()} at {new Date(post.updated_at).toLocaleTimeString()}</span>
                              </span>
                            )}
                          </div>
                        </div>
                        <div className="ml-3 sm:ml-4 flex-shrink-0">
                          <div className="w-1.5 h-1.5 sm:w-2 sm:h-2 bg-green-500 rounded-full"></div>
                        </div>
                      </div>
                    </div>
                    <div className="post-actions bg-green-50/50 p-4 sm:p-6 border-t border-green-200/50">
                      <div className="action-buttons flex justify-between items-center">
                        <button
                          className="btn btn-secondary bg-gradient-to-r from-gray-600 to-gray-700 text-white py-2 px-4 sm:px-6 rounded-xl font-semibold hover:from-gray-700 hover:to-gray-800 transition-all duration-300 shadow-md hover:shadow-lg disabled:opacity-60 disabled:cursor-not-allowed flex items-center justify-center space-x-2 touch-manipulation active:scale-95"
                          onClick={() => handleDeletePost(post.id)}
                          disabled={loading}
                        >
                          <svg className="w-3 h-3 sm:w-4 sm:h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                          </svg>
                          <span className="text-xs sm:text-sm">Delete</span>
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default Posts;