import React, { useState, useRef } from 'react';
import { mdiImageOutline, mdiVideoOutline, mdiMapMarkerOutline, mdiClose, mdiLoading } from '@mdi/js';
import BaseIcon from '../BaseIcon';
import UserAvatar from '../UserAvatar';
import { useAppDispatch, useAppSelector } from '../../stores/hooks';
import { create as createPost, setRefetch } from '../../stores/posts/postsSlice';
import FileUploader from '../Uploaders/UploadService';

export default function CreatePost() {
  const dispatch = useAppDispatch();
  const { currentUser } = useAppSelector((state) => state.auth);
  const [caption, setCaption] = useState('');
  const [files, setFiles] = useState<any[]>([]);
  const [isUploading, setIsUploading] = useState(false);
  const [isPosting, setIsPosting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const authorName = currentUser ? `${currentUser.firstName} ${currentUser.lastName}` : 'Anonymous';
  const authorAvatar = currentUser ? currentUser.avatar : null;

  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const selectedFiles = e.target.files;
    if (!selectedFiles) return;

    setIsUploading(true);
    const newFiles = [...files];
    
    for (let i = 0; i < selectedFiles.length; i++) {
      const file = selectedFiles[i];
      try {
        const remoteFile = await FileUploader.upload('posts', file, { image: file.type.startsWith('image'), size: 10 * 1024 * 1024 });
        newFiles.push({
          ...remoteFile,
          type: file.type.startsWith('image') ? 'image' : 'video'
        });
      } catch (err) {
        console.error('Upload failed', err);
      }
    }
    
    setFiles(newFiles);
    setIsUploading(false);
    if (fileInputRef.current) fileInputRef.current.value = '';
  };

  const removeFile = (index: number) => {
    setFiles(files.filter((_, i) => i !== index));
  };

  const handleSubmit = async () => {
    if (!caption && files.length === 0) return;

    setIsPosting(true);
    const postData = {
      caption,
      post_type: 'post',
      published_at: new Date().toISOString(),
      author: currentUser.id,
      images: files.filter(f => f.type === 'image'),
      video: files.find(f => f.type === 'video') || null,
      comments_enabled: true,
      is_archived: false,
    };

    try {
      await dispatch(createPost(postData)).unwrap();
      setCaption('');
      setFiles([]);
      dispatch(setRefetch(true));
    } catch (err) {
      console.error('Failed to create post', err);
    } finally {
      setIsPosting(false);
    }
  };

  return (
    <div className="bg-white dark:bg-[#1a1d23] border border-gray-200 dark:border-gray-800 rounded-2xl p-4 mb-6 max-w-lg mx-auto shadow-sm">
      <div className="flex items-start space-x-3">
        <UserAvatar username={authorName} image={authorAvatar} className="w-10 h-10 mt-1" />
        <div className="flex-1">
          <textarea
            className="w-full bg-transparent border-none focus:ring-0 text-sm dark:text-white placeholder-gray-500 resize-none"
            placeholder="What's on your mind?"
            rows={3}
            value={caption}
            onChange={(e) => setCaption(e.target.value)}
          />
          
          {/* Previews */}
          {files.length > 0 && (
            <div className="flex flex-wrap gap-2 mt-2">
              {files.map((file, idx) => (
                <div key={idx} className="relative w-20 h-20 rounded-lg overflow-hidden border border-gray-200 dark:border-gray-700">
                  {file.type === 'image' ? (
                    <img src={file.publicUrl} alt="Preview" className="w-full h-full object-cover" />
                  ) : (
                    <div className="w-full h-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center">
                      <BaseIcon path={mdiVideoOutline} size={24} className="text-gray-400" />
                    </div>
                  )}
                  <button
                    onClick={() => removeFile(idx)}
                    className="absolute top-1 right-1 bg-black/50 rounded-full p-0.5 hover:bg-black/70 transition-colors"
                  >
                    <BaseIcon path={mdiClose} size={14} className="text-white" />
                  </button>
                </div>
              ))}
              {isUploading && (
                <div className="w-20 h-20 rounded-lg border border-gray-200 dark:border-gray-700 flex items-center justify-center animate-spin">
                  <BaseIcon path={mdiLoading} size={24} className="text-pavitra-blue" />
                </div>
              )}
            </div>
          )}

          <div className="flex items-center justify-between mt-4 pt-3 border-t border-gray-100 dark:border-gray-800">
            <div className="flex items-center space-x-4">
              <button 
                className="text-gray-500 hover:text-pavitra-blue transition-colors flex items-center space-x-1"
                onClick={() => fileInputRef.current?.click()}
              >
                <BaseIcon path={mdiImageOutline} size={20} />
                <span className="text-xs font-medium">Photo</span>
              </button>
              <button 
                className="text-gray-500 hover:text-pavitra-blue transition-colors flex items-center space-x-1"
                onClick={() => fileInputRef.current?.click()}
              >
                <BaseIcon path={mdiVideoOutline} size={20} />
                <span className="text-xs font-medium">Video</span>
              </button>
              <button className="text-gray-500 hover:text-pavitra-blue transition-colors flex items-center space-x-1">
                <BaseIcon path={mdiMapMarkerOutline} size={20} />
                <span className="text-xs font-medium">Location</span>
              </button>
            </div>
            
            <button
              disabled={isPosting || isUploading || (!caption && files.length === 0)}
              onClick={handleSubmit}
              className={`
                px-6 py-1.5 rounded-full text-sm font-bold transition-all
                ${isPosting || isUploading || (!caption && files.length === 0)
                  ? 'bg-gray-100 text-gray-400 cursor-not-allowed dark:bg-gray-800'
                  : 'bg-[#00d4ff] hover:bg-[#00b4d8] text-white shadow-[0_0_15px_rgba(0,212,255,0.3)]'
                }
              `}
            >
              {isPosting ? 'Posting...' : 'Post'}
            </button>
          </div>
        </div>
      </div>
      
      <input
        type="file"
        multiple
        accept="image/*,video/*"
        className="hidden"
        ref={fileInputRef}
        onChange={handleFileSelect}
      />
    </div>
  );
}
