import { Heart, MessageCircle, Share, ThumbsUp } from "lucide-react"
import PlatformIcon from "../../UI/PlatformIcon"

// Utility functions for hashtag and URL detection and highlighting
const extractHashtags = (text) => {
  const hashtagRegex = /#[a-zA-Z0-9_]+/g
  return text.match(hashtagRegex) || []
}

const extractUrls = (text) => {
  const urlRegex = /(https?:\/\/[^\s]+)/g
  return text.match(urlRegex) || []
}

const highlightContent = (text) => {
  const hashtagRegex = /#[a-zA-Z0-9_]+/g
  const urlRegex = /(https?:\/\/[^\s]+)/g

  // Split by both hashtags and URLs, keeping the delimiters
  const parts = text.split(/(#[a-zA-Z0-9_]+|https?:\/\/[^\s]+)/g)

  return parts
    .map((part, index) => {
      if (!part) return null

      if (hashtagRegex.test(part)) {
        return (
          <span
            key={index}
            className="bg-yellow-200 dark:bg-yellow-600 text-yellow-800 dark:text-yellow-200 px-1 rounded"
          >
            {part}
          </span>
        )
      }

      if (urlRegex.test(part)) {
        return (
          <span key={index} className="text-blue-600 dark:text-blue-400">
            {part}
          </span>
        )
      }

      return part
    })
    .filter(Boolean)
}

export default function FacebookPreview({ postContent = "", postType = "feed", selectedMedia = [] }) {
  // Mock user data - in real app this would come from selected account
  const mockUser = {
    name: "James Clerk",
    username: "@jamesclerk",
    avatar: "/diverse-user-avatars.png",
    verified: false,
  }

  const hashtags = extractHashtags(postContent)

  const renderFacebookFeed = () => (
    <div className="bg-white dark:bg-zinc-900 rounded-lg border border-gray-200 dark:border-zinc-800 overflow-hidden w-full max-w-full sm:max-w-md flex flex-col">
      {/* Header */}
      <div className="p-3 sm:p-4 border-b border-gray-100 dark:border-gray-700 flex items-center gap-3">
        <PlatformIcon slug="facebook" size={24} round />
        <div className="flex-1 min-w-0">
          <h3 className="font-medium text-gray-900 dark:text-white truncate">{mockUser.name}</h3>
          <div className="flex items-center gap-1 text-sm text-gray-500 dark:text-gray-400">
            <span>Now</span>
            <div className="w-1 h-1 bg-gray-400 rounded-full"></div>
            <div className="w-3 h-3 border border-gray-400 rounded-sm flex items-center justify-center">
              <div className="w-1 h-1 bg-gray-400 rounded-full"></div>
            </div>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="p-3 sm:p-4 flex flex-col gap-4">
        <div className="text-gray-900 dark:text-white whitespace-pre-wrap break-words">
          {postContent ? highlightContent(postContent) : "What's in your mind"}
        </div>

        {hashtags.length > 0 && (
          <div className="flex flex-wrap gap-2">
            {hashtags.map((hashtag, index) => (
              <span
                key={index}
                className="bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 px-2 py-1 rounded-full text-sm font-medium"
              >
                {hashtag}
              </span>
            ))}
          </div>
        )}

        {selectedMedia.length > 0 && (
          <div className="rounded-lg overflow-hidden">
            {selectedMedia.length === 1 ? (
              selectedMedia[0].type === "video" ? (
                <video
                  src={selectedMedia[0].url || "/placeholder.svg"}
                  poster={selectedMedia[0].thumbnail}
                  controls
                  className="w-full max-h-96 object-cover rounded-lg"
                  preload="metadata"
                  type="video/mp4"
                >
                  <source src={selectedMedia[0].url} type="video/mp4" />
                  <source src={selectedMedia[0].url} type="video/webm" />
                  <source src={selectedMedia[0].url} type="video/ogg" />
                  Your browser does not support the video tag.
                </video>
              ) : (
                <img
                  src={selectedMedia[0].thumbnail || selectedMedia[0].url}
                  alt={selectedMedia[0].alt || "Post image"}
                  className="w-full max-h-96 object-cover rounded-lg"
                />
              )
            ) : (
              <div className="grid grid-cols-2 gap-1">
                {selectedMedia.slice(0, 4).map((media, idx) => (
                  <div key={media.id} className="relative aspect-square">
                    {media.type === "video" ? (
                      <video
                        src={media.url}
                        poster={media.thumbnail}
                        className="w-full h-full object-cover"
                        preload="metadata"
                        muted
                        type="video/mp4"
                      >
                        <source src={media.url} type="video/mp4" />
                        <source src={media.url} type="video/webm" />
                        <source src={media.url} type="video/ogg" />
                        Your browser does not support the video tag.
                      </video>
                    ) : (
                      <img
                        src={media.thumbnail || media.url}
                        alt={media.alt || `Post image ${idx + 1}`}
                        className="w-full h-full object-cover"
                      />
                    )}
                    {idx === 3 && selectedMedia.length > 4 && (
                      <div className="absolute inset-0 bg-black/60 flex items-center justify-center rounded">
                        <span className="text-white text-xl font-bold">+{selectedMedia.length - 4}</span>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}
      </div>

      {/* Actions */}
      <div className="border-t border-gray-100 dark:border-gray-700 p-3 sm:p-4">
        <div className="flex justify-around items-center gap-1 max-w-full">
          {["Like", "Comment", "Share"].map((action) => (
            <button
              key={action}
              className="flex items-center gap-1 px-2 py-2 text-gray-600 dark:text-gray-400 hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg text-sm min-w-0 flex-1 justify-center"
            >
              {action === "Like" && <ThumbsUp className="w-4 h-4 flex-shrink-0" />}
              {action === "Comment" && <MessageCircle className="w-4 h-4 flex-shrink-0" />}
              {action === "Share" && <Share className="w-4 h-4 flex-shrink-0" />}
            </button>
          ))}
        </div>
      </div>
    </div>
  )

  const renderFacebookReel = () => (
    <div className="bg-black rounded-lg overflow-hidden aspect-[9/16] max-w-[280px] mx-auto relative">
      {selectedMedia.length > 0 ? (
        selectedMedia[0].type === "video" ? (
          <video
            src={selectedMedia[0].url}
            poster={selectedMedia[0].thumbnail}
            className="w-full h-full object-cover"
            autoPlay
            muted
            loop
            playsInline
            type="video/mp4"
          >
            <source src={selectedMedia[0].url} type="video/mp4" />
            <source src={selectedMedia[0].url} type="video/webm" />
            <source src={selectedMedia[0].url} type="video/ogg" />
            Your browser does not support the video tag.
          </video>
        ) : (
          <img
            src={selectedMedia[0].thumbnail || selectedMedia[0].url}
            alt={selectedMedia[0].alt || "Reel image"}
            className="w-full h-full object-cover"
          />
        )
      ) : (
        <div className="absolute inset-0 flex items-center justify-center text-white">
          <div className="text-center">
            <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center mb-2 mx-auto">
              <div className="w-0 h-0 border-l-[8px] border-l-white border-y-[6px] border-y-transparent ml-1"></div>
            </div>
            <p className="text-sm">No media selected</p>
          </div>
        </div>
      )}

      {/* Overlay UI Elements */}
      <div className="absolute top-4 right-4 flex flex-col gap-4">
        <div className="w-8 h-8 bg-white/20 rounded-full flex items-center justify-center">
          <span className="text-white text-xs font-bold">111k</span>
        </div>
      </div>

      <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/80 to-transparent">
        <div className="flex items-end gap-3">
          <div className="flex-1">
            <div className="flex items-center gap-2 mb-2">
              <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center">
                <span className="text-white text-xs font-bold">f</span>
              </div>
              <span className="text-white font-medium">{mockUser.name}</span>
              <span className="text-white/70 text-sm">Now</span>
            </div>
            <p className="text-white text-sm mb-2">
              {postContent ? highlightContent(postContent) : "What's in your mind"}
            </p>
            {hashtags.length > 0 && <div className="text-cyan-400 text-sm">{hashtags.join(" ")}</div>}
          </div>

          <div className="flex flex-col gap-3">
            <button className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center text-white">
              <Heart className="w-5 h-5" />
            </button>
            <div className="text-white text-xs text-center">23k</div>

            <button className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center text-white">
              <MessageCircle className="w-5 h-5" />
            </button>

            <button className="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center text-white">
              <Share className="w-5 h-5" />
            </button>
            <div className="text-white text-xs text-center">44</div>
          </div>
        </div>
      </div>
    </div>
  )

  const renderFacebookStory = () => (
    <div className="bg-black rounded-lg overflow-hidden aspect-[9/16] max-w-[280px] mx-auto relative">
      {selectedMedia.length > 0 ? (
        selectedMedia[0].type === "video" ? (
          <video
            src={selectedMedia[0].url}
            poster={selectedMedia[0].thumbnail}
            className="w-full h-full object-cover"
            autoPlay
            muted
            loop
            playsInline
            type="video/mp4"
          >
            <source src={selectedMedia[0].url} type="video/mp4" />
            <source src={selectedMedia[0].url} type="video/webm" />
            <source src={selectedMedia[0].url} type="video/ogg" />
            Your browser does not support the video tag.
          </video>
        ) : (
          <img
            src={selectedMedia[0].thumbnail || selectedMedia[0].url}
            alt={selectedMedia[0].alt || "Story image"}
            className="w-full h-full object-cover"
          />
        )
      ) : (
        <div className="absolute inset-0 flex items-center justify-center text-white">
          <div className="text-center">
            <div className="w-16 h-16 bg-blue-600 rounded-full flex items-center justify-center mb-2 mx-auto">
              <div className="w-0 h-0 border-l-[8px] border-l-white border-y-[6px] border-y-transparent ml-1"></div>
            </div>
            <p className="text-sm">No media selected</p>
          </div>
        </div>
      )}

      {/* Story UI Elements - simpler than Reel */}
      <div className="absolute top-4 left-4 right-4">
        <div className="flex items-center gap-2">
          <div className="w-8 h-8 bg-blue-600 rounded-full flex items-center justify-center">
            <span className="text-white text-xs font-bold">f</span>
          </div>
          <span className="text-white font-medium">{mockUser.name}</span>
          <span className="text-white/70 text-sm">Now</span>
        </div>
      </div>

      {/* Story progress bar */}
      <div className="absolute top-2 left-4 right-4">
        <div className="h-0.5 bg-white/30 rounded-full">
          <div className="h-full w-1/3 bg-white rounded-full"></div>
        </div>
      </div>

      {/* Story text overlay if content exists */}
      {postContent && (
        <div className="absolute bottom-20 left-4 right-4">
          <p className="text-white text-lg font-medium text-center">{highlightContent(postContent)}</p>
        </div>
      )}
    </div>
  )

  switch (postType) {
    case "reels":
      return renderFacebookReel()
    case "story":
      return renderFacebookStory()
    default:
      return renderFacebookFeed()
  }
}
