import React, { useState, useRef } from 'react';
import { X, Image, Video, Users, Lock, Globe, Calendar, Clock, Plus, Trash2 } from 'lucide-react';
import { Post, MediaFile, SharingSettings, ContentBlock } from '../types';
import FileUpload from './FileUpload';
import ShareSettings from './ShareSettings';
import ScheduleSettings from './ScheduleSettings';

interface CreatePostProps {
  onPost: (post: Post) => void;
  onCancel: () => void;
}

const CreatePost: React.FC<CreatePostProps> = ({ onPost, onCancel }) => {
  const [title, setTitle] = useState('');
  const [contentBlocks, setContentBlocks] = useState<ContentBlock[]>([
    { id: '1', type: 'text', content: '' }
  ]);
  const [sharing, setSharing] = useState<SharingSettings>({ 
    type: 'private',
    description: 'Only you can see this post'
  });
  const [scheduledFor, setScheduledFor] = useState<Date | null>(null);
  const [showShareSettings, setShowShareSettings] = useState(false);
  const [showScheduleSettings, setShowScheduleSettings] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const addContentBlock = (type: 'text' | 'image' | 'video', afterIndex?: number) => {
    const newBlock: ContentBlock = {
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      type,
      content: ''
    };

    const insertIndex = afterIndex !== undefined ? afterIndex + 1 : contentBlocks.length;
    const newBlocks = [...contentBlocks];
    newBlocks.splice(insertIndex, 0, newBlock);
    setContentBlocks(newBlocks);
  };

  const updateContentBlock = (id: string, content: string, mediaFile?: MediaFile) => {
    setContentBlocks(prev => prev.map(block => 
      block.id === id 
        ? { ...block, content, mediaFile }
        : block
    ));
  };

  const removeContentBlock = (id: string) => {
    if (contentBlocks.length > 1) {
      setContentBlocks(prev => prev.filter(block => block.id !== id));
    }
  };

  const handleImageUpload = (blockId: string) => {
    fileInputRef.current?.click();
    fileInputRef.current!.onchange = (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (file) {
        const mediaFile: MediaFile = {
          id: Date.now().toString(),
          type: file.type.startsWith('video/') ? 'video' : 'image',
          url: URL.createObjectURL(file),
          filename: file.name
        };
        updateContentBlock(blockId, '', mediaFile);
      }
    };
  };

  const handleSubmit = () => {
    const hasContent = title.trim() || contentBlocks.some(block => 
      block.content.trim() || block.mediaFile
    );
    
    if (!hasContent) return;

    const now = new Date();
    const postTitle = title.trim() || `Post by You at ${now.toLocaleDateString()}`;
    
    // Extract media files from content blocks
    const media = contentBlocks
      .filter(block => block.mediaFile)
      .map(block => block.mediaFile!);

    const newPost: Post = {
      id: Date.now().toString(),
      title: postTitle,
      content: JSON.stringify(contentBlocks), // Store structured content
      media: media.length > 0 ? media : undefined,
      author: {
        name: 'You',
        avatar: 'https://images.pexels.com/photos/1704488/pexels-photo-1704488.jpeg?auto=compress&cs=tinysrgb&w=32&h=32&dpr=2'
      },
      timestamp: scheduledFor || now,
      scheduledFor,
      isScheduled: !!scheduledFor,
      likes: 0,
      isLiked: false,
      sharing,
      comments: []
    };

    onPost(newPost);
  };

  const getSharingIcon = () => {
    switch (sharing.type) {
      case 'public': return Globe;
      case 'groups': return Users;
      default: return Lock;
    }
  };

  const getSharingText = () => {
    switch (sharing.type) {
      case 'public': return 'Public';
      case 'groups': return 'Groups';
      default: return 'Private';
    }
  };

  const SharingIcon = getSharingIcon();

  return (
    <div className="bg-white dark:bg-gray-800 rounded-2xl shadow-lg border border-gray-200 dark:border-gray-700 overflow-hidden">
      <input
        type="file"
        ref={fileInputRef}
        accept="image/*,video/*"
        className="hidden"
      />

      {/* Header */}
      <div className="flex items-center justify-between p-4 border-b border-gray-100 dark:border-gray-700">
        <h3 className="text-lg font-semibold text-gray-900 dark:text-white">Create Post</h3>
        <button
          onClick={onCancel}
          className="text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 transition-colors p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700"
        >
          <X size={20} />
        </button>
      </div>

      {/* Content */}
      <div className="p-4">
        <div className="flex space-x-3 mb-4">
          <div className="w-10 h-10 rounded-full bg-gray-900 dark:bg-white flex items-center justify-center text-white dark:text-gray-900 font-medium">
            Y
          </div>
          <div className="flex-1">
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Post title (optional)"
              className="w-full border-none outline-none text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 text-lg font-semibold mb-2 bg-transparent"
            />
          </div>
        </div>

        {/* Content Blocks */}
        <div className="space-y-4">
          {contentBlocks.map((block, index) => (
            <div key={block.id} className="group relative">
              {block.type === 'text' ? (
                <div className="relative">
                  <textarea
                    value={block.content}
                    onChange={(e) => updateContentBlock(block.id, e.target.value)}
                    placeholder={index === 0 ? "What's on your mind?" : "Continue writing..."}
                    className="w-full resize-none border-none outline-none text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 text-base leading-relaxed min-h-[60px] focus:ring-2 focus:ring-gray-500 dark:focus:ring-gray-400 focus:ring-opacity-20 rounded-lg p-2 bg-transparent"
                    rows={3}
                  />
                  
                  {/* Add content buttons */}
                  <div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity flex space-x-1">
                    <button
                      onClick={() => addContentBlock('text', index)}
                      className="p-1 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                      title="Add text block"
                    >
                      <Plus size={16} />
                    </button>
                    <button
                      onClick={() => addContentBlock('image', index)}
                      className="p-1 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                      title="Add image"
                    >
                      <Image size={16} />
                    </button>
                    <button
                      onClick={() => addContentBlock('video', index)}
                      className="p-1 text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                      title="Add video"
                    >
                      <Video size={16} />
                    </button>
                    {contentBlocks.length > 1 && (
                      <button
                        onClick={() => removeContentBlock(block.id)}
                        className="p-1 text-gray-400 dark:text-gray-500 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20 rounded"
                        title="Remove block"
                      >
                        <Trash2 size={16} />
                      </button>
                    )}
                  </div>
                </div>
              ) : (
                <div className="relative">
                  {block.mediaFile ? (
                    <div className="relative group">
                      {block.mediaFile.type === 'image' ? (
                        <img
                          src={block.mediaFile.url}
                          alt={block.mediaFile.filename}
                          className="w-full max-h-96 object-cover rounded-lg"
                        />
                      ) : (
                        <video
                          src={block.mediaFile.url}
                          className="w-full max-h-96 object-cover rounded-lg"
                          controls
                        />
                      )}
                      <button
                        onClick={() => removeContentBlock(block.id)}
                        className="absolute top-2 right-2 bg-black/60 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                      >
                        <X size={14} />
                      </button>
                    </div>
                  ) : (
                    <div 
                      onClick={() => handleImageUpload(block.id)}
                      className="border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg p-8 text-center cursor-pointer hover:border-gray-400 dark:hover:border-gray-500 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
                    >
                      {block.type === 'image' ? (
                        <>
                          <Image size={32} className="mx-auto text-gray-400 dark:text-gray-500 mb-2" />
                          <p className="text-gray-500 dark:text-gray-400">Click to add an image</p>
                        </>
                      ) : (
                        <>
                          <Video size={32} className="mx-auto text-gray-400 dark:text-gray-500 mb-2" />
                          <p className="text-gray-500 dark:text-gray-400">Click to add a video</p>
                        </>
                      )}
                    </div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>

        {/* Share Settings Modal */}
        {showShareSettings && (
          <div className="mb-4">
            <ShareSettings
              sharing={sharing}
              onSharingChange={setSharing}
              onClose={() => setShowShareSettings(false)}
            />
          </div>
        )}

        {/* Schedule Settings Modal */}
        {showScheduleSettings && (
          <div className="mb-4">
            <ScheduleSettings
              scheduledFor={scheduledFor}
              onScheduleChange={setScheduledFor}
              onClose={() => setShowScheduleSettings(false)}
            />
          </div>
        )}
      </div>

      {/* Footer */}
      <div className="flex items-center justify-between p-4 border-t border-gray-100 dark:border-gray-700 bg-gray-50/50 dark:bg-gray-800/50">
        <div className="flex items-center space-x-2">
          <button
            onClick={() => addContentBlock('image')}
            className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
          >
            <Image size={18} />
            <span className="text-sm font-medium">Photo</span>
          </button>

          <button
            onClick={() => addContentBlock('video')}
            className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
          >
            <Video size={18} />
            <span className="text-sm font-medium">Video</span>
          </button>

          <button
            onClick={() => setShowScheduleSettings(!showScheduleSettings)}
            className={`flex items-center space-x-2 transition-colors p-2 rounded-lg ${
              scheduledFor 
                ? 'text-gray-900 dark:text-white bg-gray-200 dark:bg-gray-700' 
                : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700'
            }`}
          >
            {scheduledFor ? <Clock size={18} /> : <Calendar size={18} />}
            <span className="text-sm font-medium">
              {scheduledFor ? 'Scheduled' : 'Schedule'}
            </span>
          </button>

          <button
            onClick={() => setShowShareSettings(!showShareSettings)}
            className="flex items-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white transition-colors p-2 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700"
          >
            <SharingIcon size={18} />
            <span className="text-sm font-medium">{getSharingText()}</span>
          </button>
        </div>

        <div className="flex items-center space-x-3">
          {scheduledFor && (
            <div className="text-sm text-gray-600 dark:text-gray-400 font-medium">
              {scheduledFor.toLocaleDateString()} at {scheduledFor.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
            </div>
          )}
          <button
            onClick={handleSubmit}
            disabled={!title.trim() && !contentBlocks.some(block => block.content.trim() || block.mediaFile)}
            className="bg-gray-900 dark:bg-white text-white dark:text-gray-900 px-6 py-2 rounded-full font-medium hover:bg-gray-800 dark:hover:bg-gray-100 transform hover:scale-105 transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:shadow-none"
          >
            {scheduledFor ? 'Schedule Post' : 'Post'}
          </button>
        </div>
      </div>
    </div>
  );
};

export default CreatePost;