'use client'

import { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { LuCheck, LuCopy } from 'react-icons/lu'

import * as businessWidgetServices from '@/lib/services/business-widget-services'
import { BusinessWidget } from '@/lib/types/business-widget'
import { useAuth } from '@/lib/context/AuthContext'
import { cn } from '@/lib/utils/tw-merge'

export default function MainContent() {
  const { user } = useAuth()
  const [isLoadingInitial, setIsLoadingInitial] = useState(true)
  const [businessWidgets, setBusinessWidgets] = useState<BusinessWidget[]>([])
  const [copiedStates, setCopiedStates] = useState<Array<number>>([])

  async function handleCopy(text: string, id: number) {
    try {
      await navigator.clipboard.writeText(text)
      setCopiedStates([...copiedStates, id])

      toast.success('Successfully copied to clipboard')

      setTimeout(() => {
        setCopiedStates((prev) => {
          return prev.filter((copiedState) => copiedState !== id)
        })
      }, 1000)
    } catch {
      toast.error('Failed to copy to clipboard')
    }
  }

  useEffect(() => {
    async function fetchBusinessWidgets() {
      setIsLoadingInitial(true)

      try {
        const businessWidgetsData =
          await businessWidgetServices.getBusinessWidgets()
        setBusinessWidgets(businessWidgetsData)
      } catch {
        toast.error('Failed to load business widgets. Please try again.')
      } finally {
        setIsLoadingInitial(false)
      }
    }

    fetchBusinessWidgets()
  }, [])

  return (
    <section className="mt-8">
      <div>
        <h1 className="text-3xl font-semibold text-black mb-2">
          Business Widgets
        </h1>
        <p className="font-medium text-slate-500">
          Below are your business widgets that could be embedded on your own
          site.
        </p>
      </div>

      <div className="flex flex-wrap gap-10 mt-12">
        {isLoadingInitial
          ? Array.from({ length: 3 }).map((_, idx) => (
              <div
                key={idx}
                className="w-200 rounded-xl border border-gray-200 bg-white p-5 animate-pulse"
              >
                <div className="h-5 bg-slate-200 rounded w-1/3 mb-2" />
                <div className="relative">
                  <div className="bg-slate-50 p-4 rounded-md border border-slate-200 space-y-2">
                    <div className="h-4 bg-slate-200 rounded w-3/4" />
                    <div className="h-4 bg-slate-100 rounded w-1/2" />
                    <div className="h-4 bg-slate-100 rounded w-2/3" />
                  </div>
                  <div className="absolute top-3 right-3 h-9 w-9 rounded-md bg-slate-200" />
                </div>
              </div>
            ))
          : businessWidgets?.map((businessWidget, idx) => {
              const scriptCode = `<script src="https://widget.balirsv.com/dist/index.js"></script><ticket-search-widget widgetid="${businessWidget.username}" refcode="${user?.referral_code}"></ticket-search-widget>`

              return (
                <div
                  key={idx}
                  className="w-200 rounded-xl border border-gray-200 bg-white p-5"
                >
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">
                    {businessWidget.name}
                  </h3>

                  <div className="relative">
                    <pre className="bg-slate-50 p-4 rounded-md border border-slate-200 overflow-x-auto">
                      <code className="text-sm font-mono text-gray-600">
                        <span className="text-blue-500">
                          {'<!-- Add this script before closing body tag -->'}
                        </span>
                        <br />
                        {`<script src="https://widget.balirsv.com/dist/index.js"></script>`}
                        <br />
                        <br />
                        <span className="text-blue-500">
                          {
                            '<!-- Add the widget where you want it to appear -->'
                          }
                        </span>
                        <br />
                        {`<ticket-search-widget widgetid="${businessWidget.username}" refcode="${user?.referral_code}"></ticket-search-widget>`}
                      </code>
                    </pre>
                    <button
                      onClick={() => handleCopy(scriptCode, idx)}
                      className={cn(
                        'absolute top-3 right-3 p-2 rounded-md transition-colors',
                        copiedStates.includes(idx)
                          ? 'bg-green-500 text-white'
                          : ' bg-gray-300 text-gray-700 hover:bg-gray-400',
                      )}
                    >
                      {copiedStates.includes(idx) ? (
                        <LuCheck className="w-5 h-5" />
                      ) : (
                        <LuCopy className="w-5 h-5" />
                      )}
                    </button>
                  </div>
                </div>
              )
            })}
      </div>
    </section>
  )
}
