'use client'

import { useEffect, useState } from 'react'
import * as motion from 'framer-motion/m'
import { Link } from '@/i18n/navigation'
import { useTranslations } from 'next-intl'
import { ShoppingBag, Heart, MapPin, Package, Truck, Clock } from 'lucide-react'
import RecentOrders, { type RecentOrder } from './RecentOrders'
import { useAccountUser } from './AccountUserContext'
import { useWishlistStore } from '@/store/wishlistStore'

interface DashboardStats {
  totalOrders: number
  savedAddresses: number
  recentOrders: RecentOrder[]
}

export default function DashboardOverview() {
  const user = useAccountUser()
  const t = useTranslations('Account.dashboard')
  const { items: wishlistItems, fetchWishlist } = useWishlistStore()
  const [stats, setStats] = useState<DashboardStats>({ totalOrders: 0, savedAddresses: 0, recentOrders: [] })
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let cancelled = false
    fetchWishlist()

    Promise.all([
      fetch('/api/frontend/orders?limit=3', { credentials: 'include' }).then((r) => r.json()),
      fetch('/api/frontend/addresses', { credentials: 'include' }).then((r) => r.json()),
    ])
      .then(([ordersRes, addressesRes]) => {
        if (cancelled) return
        setStats({
          totalOrders: ordersRes?.success ? ordersRes.data.pagination.total : 0,
          savedAddresses: addressesRes?.success ? addressesRes.data.length : 0,
          recentOrders: ordersRes?.success ? ordersRes.data.orders : [],
        })
      })
      .finally(() => {
        if (!cancelled) setLoading(false)
      })

    return () => { cancelled = true }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const statCards = [
    { label: t('statOrders'), value: stats.totalOrders, icon: ShoppingBag },
    { label: t('statWishlist'), value: wishlistItems.length, icon: Heart },
    { label: t('statAddresses'), value: stats.savedAddresses, icon: MapPin },
  ]

  return (
    <div className="space-y-8">
      {/* Welcome Section */}
      <div className="bg-gradient-primary rounded-xl p-6 text-white">
        <h2 className="text-xl font-bold mb-1">{t('welcome', { name: user.name })} 👋</h2>
        <p className="text-white/80 text-sm">{t('subtitle')}</p>
      </div>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
        {statCards.map((stat, index) => (
          <motion.div
            key={stat.label}
            initial={{ opacity: 0, y: 20 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ delay: index * 0.1 }}
            className="bg-gray-50 rounded-xl p-4 text-center"
          >
            <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center mx-auto mb-3">
              <stat.icon className="w-5 h-5 text-primary" />
            </div>
            <div className="text-xl font-bold text-dark">{loading ? '—' : stat.value}</div>
            <div className="text-xs text-gray-custom">{stat.label}</div>
          </motion.div>
        ))}
      </div>

      {/* Recent Orders */}
      {!loading && <RecentOrders orders={stats.recentOrders} />}

      {/* Quick Actions */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
        <Link
          href="/"
          className="flex items-center justify-center gap-2 p-3 bg-primary/10 text-primary rounded-lg text-sm font-medium hover:bg-primary hover:text-white transition-all"
        >
          <Package size={16} />
          {t('shopNow')}
        </Link>
        <Link
          href="/account/orders"
          className="flex items-center justify-center gap-2 p-3 bg-gray-100 text-dark rounded-lg text-sm font-medium hover:bg-primary hover:text-white transition-all"
        >
          <Truck size={16} />
          {t('trackOrder')}
        </Link>
        <Link
          href="/account/wishlist"
          className="flex items-center justify-center gap-2 p-3 bg-gray-100 text-dark rounded-lg text-sm font-medium hover:bg-primary hover:text-white transition-all"
        >
          <Heart size={16} />
          {t('wishlist')}
        </Link>
        <Link
          href="/offers"
          className="flex items-center justify-center gap-2 p-3 bg-gray-100 text-dark rounded-lg text-sm font-medium hover:bg-primary hover:text-white transition-all"
        >
          <Clock size={16} />
          {t('offers')}
        </Link>
      </div>
    </div>
  )
}
