'use client'

import React, {
  Dispatch,
  SetStateAction,
  useEffect,
  useMemo,
  useRef,
} from 'react'
import { Avatar, Badge, Button, Card } from 'flowbite-react'
import { isSameDay } from 'date-fns'
import { FiClock, FiGrid } from 'react-icons/fi'
import { useRouter } from 'next/navigation'

import buttonTheme from '@/lib/themes/button'
import { formatToMYT } from '@/lib/utils/date'
import { cn } from '@/lib/utils/tw-merge'
import { useAuth } from '@/lib/context/AuthContext'
import { Merchant } from '../types'

interface CardGridProps {
  merchants: Merchant[]
  hasMore?: boolean
  isLoadingMore?: boolean
  isLoadingInitial?: boolean
  setModal: Dispatch<SetStateAction<ModalState>>
  onLoadMore?: () => void
  setMerchant: Dispatch<SetStateAction<Merchant | null>>
}

export default function CardGrid({
  merchants,
  hasMore = false,
  isLoadingMore = false,
  isLoadingInitial = false,
  setModal,
  onLoadMore,
  setMerchant,
}: CardGridProps) {
  const router = useRouter()
  const { user } = useAuth()
  const sentinelRef = useRef<HTMLDivElement | null>(null)

  useEffect(() => {
    if (!hasMore) return
    if (!sentinelRef.current) return

    const el = sentinelRef.current
    const io = new IntersectionObserver(
      (entries) => {
        const first = entries[0]
        if (first.isIntersecting && !isLoadingMore) {
          onLoadMore?.()
        }
      },
      { rootMargin: '200px 0px' },
    )

    io.observe(el)
    return () => io.unobserve(el)
  }, [hasMore, isLoadingMore, onLoadMore])

  function handleDelete(merchant: Merchant) {
    setModal({ type: 'delete', isOpened: true })
    setMerchant(merchant)
  }

  function handleEdit(merchant: Merchant) {
    setModal({ type: 'edit', isOpened: true })
    setMerchant(merchant)
  }

  const skeletonItems = useMemo(() => Array.from({ length: 8 }), [])

  return (
    <div className="mt-8">
      {isLoadingInitial ? (
        <div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
          role="list"
        >
          {skeletonItems.map((_, idx) => (
            <article
              key={idx}
              className="bg-white rounded-lg border border-slate-100 p-4 animate-pulse"
            >
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-slate-200" />
                <div className="flex-1 space-y-2">
                  <div className="h-4 bg-slate-200 rounded w-3/4" />
                  <div className="h-3 bg-slate-100 rounded w-1/2" />
                </div>
              </div>
              <div className="mt-4 h-6 bg-slate-100 rounded w-20" />
              <div className="mt-6 grid gap-2">
                <div className="h-4 bg-slate-100 rounded" />
                <div className="h-4 bg-slate-100 rounded" />
              </div>
            </article>
          ))}
        </div>
      ) : merchants?.length === 0 ? (
        <div className="text-center text-slate-500">No data available</div>
      ) : (
        <div
          className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4"
          role="list"
        >
          {merchants?.map((merchant) => (
            <Card
              key={merchant.id}
              className={cn(
                'rounded-lg p-0 flex flex-col transition-shadow bg-gradient-to-br from-white to-slate-50 border border-slate-200 shadow-none',
              )}
            >
              <div className="flex items-center gap-3">
                <Avatar
                  alt="User Avatar"
                  img={`https://api.dicebear.com/9.x/initials/svg?seed=${merchant?.name}&backgroundType=gradientLinear`}
                  rounded
                  size={'md'}
                />

                <div className="min-w-0 flex-1">
                  <h3
                    className="truncate text-black font-semibold"
                    title={merchant?.name}
                  >
                    {merchant?.name}
                  </h3>
                  <p className="truncate text-sm text-slate-500">
                    @{merchant?.username}
                  </p>
                </div>
              </div>
              <div className="flex items-center gap-2">
                <Badge color="green" className="font-medium w-fit">
                  {merchant?.code}
                </Badge>
              </div>
              {user?.role === 'super_admin' && (
                <React.Fragment>
                  <dl className="mt-4 grid gap-2 text-sm">
                    <div className="flex flex-col">
                      <dt className="text-slate-500 flex items-center gap-2">
                        <FiClock />
                        Created
                      </dt>
                      <dd
                        className={
                          isSameDay(new Date(), new Date(merchant?.created_at))
                            ? 'text-green-600 font-medium'
                            : ''
                        }
                      >
                        {formatToMYT(merchant?.created_at)}
                      </dd>
                    </div>
                    <div className="flex flex-col mt-2">
                      <dt className="text-slate-500 flex items-center gap-2">
                        <FiClock /> Updated
                      </dt>
                      <dd
                        className={
                          isSameDay(new Date(), new Date(merchant?.updated_at))
                            ? 'text-green-600 font-medium'
                            : ''
                        }
                      >
                        {formatToMYT(merchant?.updated_at)}
                      </dd>
                    </div>
                  </dl>
                </React.Fragment>
              )}

              {user?.role !== 'super_admin' && (
                <div className="mt-4">
                  <Button
                    outline
                    color="blue"
                    theme={buttonTheme.button}
                    size="sm"
                    className="flex-1 w-full"
                    onClick={() =>
                      router.push(`/merchant-dashboard/${merchant?.id}`)
                    }
                  >
                    <FiGrid className="mr-2" />
                    Open Dashboard
                  </Button>
                </div>
              )}

              {user?.role === 'super_admin' && (
                <div className="flex items-center gap-4">
                  <Button
                    color="red"
                    theme={buttonTheme.button}
                    size="sm"
                    className="w-full"
                    onClick={() => handleDelete(merchant)}
                  >
                    Delete
                  </Button>
                  <Button
                    color="dark"
                    theme={buttonTheme.button}
                    size="sm"
                    className="w-full"
                    onClick={() => handleEdit(merchant)}
                  >
                    Edit Admins
                  </Button>
                </div>
              )}
            </Card>
          ))}

          {isLoadingMore && (
            <React.Fragment>
              {Array.from({ length: 4 }).map((_, idx) => (
                <div
                  key={idx}
                  className="bg-white rounded-lg shadow-sm border border-slate-100 p-4 animate-pulse h-min"
                >
                  <div className="flex items-center gap-3">
                    <div className="w-12 h-12 rounded-full bg-slate-200" />
                    <div className="flex-1 space-y-2">
                      <div className="h-4 bg-slate-200 rounded w-3/4" />
                      <div className="h-3 bg-slate-100 rounded w-1/2" />
                    </div>
                  </div>
                  <div className="mt-4 h-6 bg-slate-100 rounded w-20" />
                  <div className="mt-3 grid grid-cols-2 gap-2">
                    <div className="h-4 bg-slate-100 rounded" />
                    <div className="h-4 bg-slate-100 rounded" />
                  </div>
                </div>
              ))}
            </React.Fragment>
          )}
        </div>
      )}

      {/* Infinite scroll sentinel and loader (mobile card view) */}
      <div className="mt-4 flex flex-col items-center">
        <div ref={sentinelRef} className="h-1 w-full" />
        {!hasMore && merchants.length > 0 && (
          <p className="text-xs text-slate-400 mt-2">No more results</p>
        )}
      </div>
    </div>
  )
}
