import React, { useEffect, useMemo, useState } from 'react'
import { Merchant } from '../merchants/types'
import * as merchantServices from '@/lib/services/merchant-services'
import { toast } from 'react-toastify'
import { Avatar, Badge, Button, Card } from 'flowbite-react'
import { cn } from '@/lib/utils/tw-merge'
import buttonTheme from '@/lib/themes/button'
import { useRouter } from 'next/navigation'
import { FiGrid } from 'react-icons/fi'

export default function LastViewedMerchant() {
  const router = useRouter()
  const [isLoading, setIsLoading] = useState(true)
  const [merchants, setMerchants] = useState<Merchant[]>([])

  useEffect(() => {
    async function fetchMerchants() {
      try {
        const data = await merchantServices.getLastVisitedMerchants(4)
        setMerchants(data)
      } catch {
        toast.error('Oops! something went wrong while fetching merchants.')
      } finally {
        setIsLoading(false)
      }
    }

    fetchMerchants()
  }, [])

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

  return (
    <section className="mt-16 max-w-7xl">
      <h2 className="text-2xl font-semibold mb-6">Last Viewed Merchants</h2>

      <div className="max-w-7xl">
        {isLoading ? (
          <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-slate-500">No merchants viewed</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>

                <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>
              </Card>
            ))}
          </div>
        )}
      </div>
    </section>
  )
}
