'use client'
import React, { useEffect, useState } from 'react'
import Layout from '../layout/Layout'
import { translate } from '@/utils/translation'
import Breadcrumb from '../breadcrumb/Breadcrumb'
import { NotificationPrefCard } from '../commonComponents/commonCards/NotificationPrefCard'
import { useGetNotificationPrefs } from '@/hooks/queries/useGetNotificationPrefs'
import Skeleton from 'react-loading-skeleton'
import { notificationPrefApi } from '@/utils/api/api'
import toast from 'react-hot-toast'

const NOTIFICATION_PREF_META = {
    news: { titleKey: 'newsNotification', descKey: 'newsNotificationDesc' },
    podcasts: { titleKey: 'podcastNotification', descKey: 'podcastNotificationDesc' },
    alerts: { titleKey: 'marketAlertNotification', descKey: 'marketAlertNotificationDesc' },
    comments: { titleKey: 'commentReplyNotification', descKey: 'commentReplyNotificationDesc' },
    announcements: { titleKey: 'promotionalNotification', descKey: 'promotionalNotificationDesc' },
}

const mapPrefsToState = (data = []) => data.map(({ id, key, enabled }) => ({
    id,
    key,
    ...NOTIFICATION_PREF_META[key],
    checked: Boolean(enabled),
}))

const NotificationPref = () => {

    const { data: notificationPrefsData, isLoading: loading, isError, error } = useGetNotificationPrefs();

    const prefs = notificationPrefsData?.data;

    const [preferences, setPreferences] = useState(mapPrefsToState(prefs));

    useEffect(() => {
        if (isError) {
            console.log('error in notification-prefs', error?.message)
        }
    }, [isError])

    useEffect(() => {
        if (prefs) {
            setPreferences(mapPrefsToState(prefs))
        }
    }, [prefs])

    const togglePreference = (id) => {
        setPreferences((prev) => prev.map((pref) => pref.id === id ? { ...pref, checked: !pref.checked } : pref))
    }

    const finalSubmit = async (e) => {
        e.preventDefault()
        const payload = preferences.map(({ id, checked }) => ({
            notification_type_id: id,
            status: checked ? 1 : 0,
        }))

        try {
            const { data } = await notificationPrefApi.updateNotificationPrefs(payload)
            if (!data?.error) {
                setPreferences(mapPrefsToState(data?.data))
                toast.success(translate('updateSuccessfully'))
            } else {
                toast.error(data?.message)
            }
        } catch (error) {
            toast.error(translate('somethingMSg'))
            console.log(error)
        }
    }

    return (
        <Layout>
            <Breadcrumb secondElement={translate('notificationPref')} />

            <section className='userBasedCategories container mt-8 md:mt-12 pb-12 flex flex-col gap-8 md:gap-12'>
                <div className='bg-white dark:secondaryBg rounded-2xl flex items-center justify-between py-3 px-4'>
                    <h2 className=' font-medium text-lg md:text-xl textPrimary'>
                        {translate('notificationPref')}
                    </h2>
                    <button type='submit' className='commonBtn md:text-[18px] uppercase md:!py-4 md:!px-8'
                        onClick={e => finalSubmit(e)}
                    >{translate('saveLbl')}</button>
                </div>
                <div className='grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6'>
                    {
                        loading ?
                            Array.from({ length: 5 }).map((_, index) => (
                                <div key={index} className="flex items-start justify-between gap-4 rounded-[12px] border border-[#1B2D511A] bg-white p-4">
                                    <div className="flex flex-col gap-2 flex-1">
                                        {/* Title */}
                                        <Skeleton width="45%" height={24} borderRadius={6} />

                                        {/* Description */}
                                        <Skeleton width="90%" height={16} borderRadius={4} />
                                    </div>

                                    {/* Checkbox */}
                                    <Skeleton
                                        circle
                                        width={24}
                                        height={24}
                                        containerClassName="shrink-0"
                                    />
                                </div>
                            ))

                            :
                            preferences?.map((pref) => (
                                <NotificationPrefCard
                                    key={pref.id}
                                    title={translate(pref.titleKey)}
                                    description={translate(pref.descKey)}
                                    checked={pref.checked}
                                    onToggle={() => togglePreference(pref.id)}
                                />
                            ))
                    }
                </div>
            </section>
        </Layout>
    )
}

export default NotificationPref