import React, { useEffect } from 'react'
import { useAppDispatch, useAppSelector } from '../stores/hooks'
import { fetch } from '../stores/media_assets/media_assetsSlice'
import BaseButton from './BaseButton'
import { mdiHeart, mdiComment, mdiShareVariant, mdiDotsHorizontal } from '@mdi/js'
import BaseIcon from './BaseIcon'
import LoadingSpinner from './LoadingSpinner'

const ActivityFeed = () => {
  const dispatch = useAppDispatch()
  const { media_assets, loading } = useAppSelector((state) => state.media_assets)

  useEffect(() => {
    dispatch(fetch({ query: '?limit=10' }))
  }, [dispatch])

  if (loading && media_assets.length === 0) {
    return (
      <div className="flex justify-center py-10">
        <LoadingSpinner />
      </div>
    )
  }

  if (media_assets.length === 0) {
    return (
      <div className="text-center py-10 text-gray-500 italic">
        No recent activities found.
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {media_assets.map((asset: any) => (
        <div key={asset.id} className="bg-white dark:bg-dark-900 border border-gray-200 dark:border-dark-700 rounded-xl shadow-sm overflow-hidden transition-all hover:shadow-md">
          {/* Header */}
          <div className="p-4 flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-10 h-10 rounded-full bg-pavitra-100 flex items-center justify-center text-pavitra-600 font-bold uppercase">
                {asset.uploaded_by?.firstName?.charAt(0) || 'U'}
              </div>
              <div>
                <p className="font-bold text-gray-900 dark:text-white leading-none mb-1">
                  {asset.uploaded_by ? `${asset.uploaded_by.firstName} ${asset.uploaded_by.lastName || ''}` : 'System User'}
                </p>
                <p className="text-xs text-gray-500">
                  {asset.captured_at ? new Date(asset.captured_at).toLocaleString() : new Date(asset.createdAt).toLocaleString()}
                </p>
              </div>
            </div>
            <button className="text-gray-400 hover:text-gray-600">
              <BaseIcon path={mdiDotsHorizontal} size={20} />
            </button>
          </div>

          {/* Caption */}
          {asset.caption && (
            <div className="px-4 pb-3">
              <p className="text-gray-800 dark:text-gray-200">{asset.caption}</p>
              {asset.tags && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {asset.tags.split(',').map((tag: string) => (
                    <span key={tag} className="text-xs font-medium text-pavitra-600 bg-pavitra-50 px-2 py-0.5 rounded-full">
                      #{tag.trim()}
                    </span>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Media/Thumbnails */}
          {(asset.images?.length > 0 || asset.attachments?.length > 0) && (
            <div className={`grid gap-1 border-y border-gray-100 dark:border-dark-800 ${asset.images?.length + asset.attachments?.length > 1 ? 'grid-cols-2' : 'grid-cols-1'}`}>
              {[...(asset.images || []), ...(asset.attachments || [])].map((file: any, index: number) => {
                const isImage = file.name?.match(/\.(jpg|jpeg|png|gif|webp)$/i)
                return (
                  <div key={file.id} className={`relative bg-gray-100 dark:bg-dark-800 overflow-hidden ${index === 0 && asset.images?.length + asset.attachments?.length === 3 ? 'row-span-2' : ''}`}>
                    {isImage ? (
                      <img 
                        src={file.publicUrl} 
                        alt={file.name} 
                        className="w-full h-full object-cover max-h-[400px] hover:scale-105 transition-transform duration-500 cursor-pointer"
                      />
                    ) : (
                      <div className="flex flex-col items-center justify-center py-12 px-4 text-gray-500">
                        <div className="w-12 h-12 bg-gray-200 rounded-lg flex items-center justify-center mb-2">
                          <span className="text-xs font-bold uppercase">{file.name?.split('.').pop()}</span>
                        </div>
                        <span className="text-xs truncate w-full text-center">{file.name}</span>
                      </div>
                    )}
                  </div>
                )
              })}
            </div>
          )}

          {/* Actions */}
          <div className="p-3 flex items-center justify-between border-t border-gray-50 dark:border-dark-800">
            <div className="flex gap-4">
              <button className="flex items-center gap-1.5 text-gray-500 hover:text-red-500 transition-colors">
                <BaseIcon path={mdiHeart} size={20} />
                <span className="text-xs font-medium">Like</span>
              </button>
              <button className="flex items-center gap-1.5 text-gray-500 hover:text-pavitra-500 transition-colors">
                <BaseIcon path={mdiComment} size={20} />
                <span className="text-xs font-medium">Comment</span>
              </button>
              <button className="flex items-center gap-1.5 text-gray-500 hover:text-blue-500 transition-colors">
                <BaseIcon path={mdiShareVariant} size={20} />
                <span className="text-xs font-medium">Share</span>
              </button>
            </div>
            {asset.source && (
              <span className="text-[10px] text-gray-400 uppercase tracking-wider">Source: {asset.source}</span>
            )}
          </div>
        </div>
      ))}
      <div className="flex justify-center pt-4">
        <BaseButton label="Load More" color="white" outline />
      </div>
    </div>
  )
}

export default ActivityFeed
