import Link from 'next/link'
import { FaRegComment } from 'react-icons/fa'
// import { FaLink } from 'react-icons/fa6'
// import { MdDelete, MdEdit } from 'react-icons/md'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { CgLoadbarSound } from 'react-icons/cg'
import { FaRegStar, FaStar } from 'react-icons/fa'
import { FcLike } from 'react-icons/fc'
import { FiHeart } from 'react-icons/fi'
import { Post } from '../../../type'
import { DropDownShare } from '../atoms/DropDownShare'
import Modal from '../atoms/Modal'

interface CardPerfilProps {
  post: Post
}

export function CardPerfil({ post }: CardPerfilProps) {
  // const { postData, updatePostData } = usePostContext()
  const {
    description,
    title,
    Category,
    slug,
    url,
    Like,
    id,
    comments,
    views,
    twitterShareCount,
    whatsappShareCount,
    Favorite
  } = post
  const { data: session } = useSession()
  // const likeOfUser = Like?.some((user) => user.userEmail === session?.user?.email)
  const [isLike, setIsLike] = useState<boolean>()
  const [isFavorite, setIsFavorite] = useState<boolean>()
  const [likesCount, setLikesCount] = useState<number>(Like?.length || 0)
  const [favoriteCount, setFavoriteCount] = useState<number>(Favorite?.length || 0)
  let [isOpen, setIsOpen] = useState(false)
  const router = useRouter()

  useEffect(() => {
    if (session && Like?.some((like) => like?.userEmail === session?.user?.email)) {
      setIsLike(true)
    } else {
      setIsLike(false)
    }
  }, [Like, session])

  useEffect(() => {
    if (session && Favorite?.some((fav) => fav?.userEmail === session?.user?.email)) {
      setIsFavorite(true)
    } else {
      setIsFavorite(false)
    }
  }, [Favorite, session])

  const handleAddLike = async () => {
    if (!session) {
      setIsOpen(true)
      return
    }
    const response = await fetch(`/api/like`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: session.user.email,
        postId: id,
        session: session
      })
    })
    const data = await response.json()
    if (response.ok) {
      data && setIsLike(true)
      setLikesCount((prevCount) => prevCount + 1)
    } else {
      console.error('Error al dar like:', data.error)
    }
  }
  const handleDeleteLike = async () => {
    if (!session) {
      setIsOpen(true)
      return
    }
    const response = await fetch('/api/like', {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: session.user.email,
        postId: id,
        session: session
      })
    })

    const data = await response.json()

    if (response.ok) {
      setIsLike(false)
      setLikesCount((prevCount) => Math.max(0, prevCount - 1))
    } else {
      console.error('Error al quitar like:', data.error)
    }
  }
  const handleAddFavorite = async () => {
    if (!session) {
      setIsOpen(true)
      return
    }
    const response = await fetch(`/api/favorite`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: session.user.email,
        postId: id,
        session: session
      })
    })
    const data = await response.json()
    if (response.ok) {
      data && setIsFavorite(true)
      setFavoriteCount((prevCount) => prevCount + 1)
    } else {
      console.error('Error al dar like:', data.error)
    }
  }
  const handleDeleteFavorite = async () => {
    if (!session) {
      setIsOpen(true)
      return
    }
    const response = await fetch('/api/favorite', {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        email: session.user.email,
        postId: id,
        session: session
      })
    })

    const data = await response.json()

    if (response.ok) {
      setIsFavorite(false)
      setFavoriteCount((prevCount) => Math.max(0, prevCount - 1))
    } else {
      console.error('Error al quitar like:', data.error)
    }
  }
  return (
    <div
      className="flex flex-row rounded-xl border-black border-4 lg:gap-4 lg:p-3 p-1 mb-5 justify-center items-center "
      style={{ backgroundColor: `${Category?.color}80` }}
    >
      {/* <div className="lg:block hidden justify-center items-start">
        <div
          className="relative h-[40px] w-[40px] border-white border-2 m-2 p-1 rounded-xl"
          style={{ backgroundColor: `${Category?.color}` }}
        >
          <Image
            src={`/images/${Category?.img}.svg`}
            height={100}
            width={100}
            alt="img post"
            className="w-full h-full object-cover"
          ></Image>
        </div>
      </div> */}
      <div className="flex flex-col w-full justify-between m-2">
        <div className="flex">
          <Link href={`/post/${slug}`}>
            <div className="flex text-center lg:text-left">
              <h3 className="flex text-gray-700 mb-4 hover:opacity-50 lg:text-lg text-xs font-extrabold ">{title}</h3>
            </div>
          </Link>
        </div>
        <div className="flex md:justify-between justify-center items-center">
          <div
            className={`md:flex hidden justify-between items-center px-4 py-1 w-fit h-10 rounded-xl border-[1px200psx20] border-black border-solid gap-2 `}
            style={{ backgroundColor: Category?.color }}
          >
            <div>
              <p className="text-sm font-bold	">{Category?.title}</p>
            </div>
          </div>
          <div className="flex md:justify-end justify-start gap-0 mobile:gap-2">
            {/* <div className="flex items-center justify-center bg-white rounded-full w-8 h-8 hover:opacity-50 hover:cursor-pointer">
              <a href={url} target="_blank" rel="noopener noreferrer">
                <FaLink className="w-5 h-5" />
              </a>
            </div> */}
            <div className="flex items-center">
              <div
                className="flex items-center justify-center"
                onClick={() => {
                  isLike ? handleDeleteLike() : handleAddLike()
                }}
              >
                {isLike ? (
                  <FcLike className="w-5 h-5 cursor-pointer hover:scale-110 " />
                ) : (
                  <FiHeart className="w-5 h-5 cursor-pointer hover:opacity-50 hover:scale-110" />
                )}

                {/* <AiOutlineLike className="w-5 h-5" /> */}
              </div>
              <span className="text-xs text-gray-600 w-4 h-4 flex justify-center items-center font-bold">
                {likesCount}
              </span>
            </div>
            <div className="flex items-center">
              <div
                className="flex items-center justify-center"
                onClick={() => {
                  isFavorite ? handleDeleteFavorite() : handleAddFavorite()
                }}
              >
                {isFavorite ? (
                  <FaStar className="w-5 h-5 cursor-pointer hover:scale-110 text-yellow-500" />
                ) : (
                  <FaRegStar className="w-5 h-5 cursor-pointer hover:scale-110" />
                )}
                <span className="text-xs text-gray-600 w-4 h-4 flex justify-center items-center font-bold">
                  {favoriteCount}
                </span>
              </div>
            </div>
            <div className="flex items-center">
              <Link href={`/post/${slug}`}>
                <div className="flex items-center justify-center  w-5 h-5 hover:bg-opacity-80 hover:cursor-pointer hover:opacity-50 hover:scale-110">
                  <FaRegComment className="w-5 h-5" />
                </div>
              </Link>
              <span className="text-xs text-gray-600 w-4 h-4 flex justify-center items-center font-bold ">
                {comments?.length}
              </span>{' '}
            </div>
            <div className="flex items-center ">
              <div className="">
                <DropDownShare slug={slug} id={id} counTwitter={twitterShareCount} countWhatsapp={twitterShareCount} />
              </div>
              <span className="text-xs text-gray-600 w-4 h-4 flex justify-center items-center font-bold">
                {twitterShareCount + whatsappShareCount}
              </span>{' '}
            </div>
            <div className="flex items-center">
              <CgLoadbarSound className="w-6 h-6" />
              <span className="text-xs text-gray-600 w-4 h-4 flex justify-center items-center font-bold">
                {views}
              </span>{' '}
            </div>
          </div>
        </div>
      </div>
      <Modal
        setIsOpen={setIsOpen}
        isOpen={isOpen}
        icon={true}
        tittle="No estas logeado"
        description="No puedes comentar sin estar registrado antes."
        textTrue="Login"
        textFalse="Cancelar"
        functionTrue={() => router.push('/login')}
        functionFalse={() => router.back()}
      />
    </div>
  )
}
