'use client';

import { useEffect, useState } from 'react';
import Link from 'next/link';
import api from '@/lib/axios';
import { useAuthStore } from '@/store/auth';
import { Gift } from 'lucide-react';
import { PointExpiryWarning } from '@/components/PointExpiryWarning';
import { formatDate, formatPromoPeriod } from '@/lib/dateUtils';

interface Promotion {
  id: number; name: string; description: string;
  reward_method: string; start_date: string; end_date: string;
  start_time: string | null; end_time: string | null;
  start_datetime: string | null; end_datetime: string | null;
  banner_image: string | null;
}
interface Product {
  id: number; name: string; price: number; image_url: string | null;
}

interface UserProfile {
  full_name: string;
  total_points: number;
  point_expiry_date?: string;
  point_expiry_date_formatted?: string;
  points_expired?: boolean;
  days_until_expiry?: number;
  expiry_warning?: boolean;
}

const rewardLabel: Record<string, string> = {
  hadiah_langsung: 'Hadiah Langsung', undian: 'Undian', point_reward: 'Point Reward',
};

function formatPrice(price: number) {
  return 'Rp ' + Number(price).toLocaleString('id-ID');
}

export default function DashboardPage() {
  const user = useAuthStore((s) => s.user);
  const { setAuth, token } = useAuthStore();
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [promotions, setPromotions] = useState<Promotion[]>([]);
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    api.get('/end-user/profile').then((r) => {
      const profileData = r.data.data;
      setUserProfile(profileData);
      if (token) setAuth(profileData, token);
    }).catch(() => {});

    api.get('/end-user/promotions')
      .then((r) => setPromotions(r.data.data ?? []))
      .catch(() => {})
      .finally(() => setLoading(false));

    api.get('/content')
      .then((r) => setProducts(r.data.data?.products ?? []))
      .catch(() => {});
  }, []);

  return (
    <div>
      {/* Welcome card */}
      <div className="bg-gradient-to-r from-blue-700 to-blue-800 text-white rounded-2xl p-6 mb-8">
        <p className="text-blue-200 text-sm">Selamat datang,</p>
        <h1 className="text-2xl font-bold">{user?.full_name}</h1>
        <div className="mt-3 flex items-center gap-2">
          <span className="bg-white/20 rounded-full px-3 py-1 text-sm">
            {user?.total_points ?? 0} Poin
          </span>
          {promotions.length > 0 && (
            <Link href="/dashboard/claim"
              className="bg-white text-blue-700 rounded-full px-3 py-1 text-sm font-medium hover:bg-blue-50 transition">
              Klaim Sekarang →
            </Link>
          )}
        </div>
      </div>

      {/* Point Expiry Warning */}
      {userProfile?.point_expiry_date && (
        <div className="mb-6">
          <PointExpiryWarning
            expiryDate={userProfile.point_expiry_date}
            expiryDateFormatted={userProfile.point_expiry_date_formatted || userProfile.point_expiry_date}
            daysUntilExpiry={userProfile.days_until_expiry || 0}
            isExpired={userProfile.points_expired || false}
            expiryWarning={userProfile.expiry_warning || false}
          />
        </div>
      )}

      {/* Produk Promo */}
      {products.length > 0 && (
        <div className="mb-8">
          <h2 className="text-base font-bold text-gray-800 mb-3">Produk Promo</h2>
          <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
            {products.map((p) => (
              <div key={p.id} className="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition">
                <div className="aspect-square bg-gray-100 flex items-center justify-center overflow-hidden">
                  {p.image_url
                    ? <img src={p.image_url} alt={p.name} className="w-full h-full object-cover" />
                    : <Gift className="w-10 h-10 text-gray-300" />
                  }
                </div>
                <div className="p-2.5">
                  <p className="text-xs font-semibold text-gray-800 line-clamp-2 leading-tight">{p.name}</p>
                  <p className="text-xs text-blue-600 font-medium mt-1">{formatPrice(p.price)}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Active promotions */}
      <h2 className="text-lg font-bold text-gray-800 mb-4">Promosi Aktif</h2>
      {loading ? (
        <p className="text-gray-400 text-sm">Memuat...</p>
      ) : promotions.length === 0 ? (
        <p className="text-gray-400 text-sm">Belum ada promosi aktif.</p>
      ) : (
        <div className="space-y-3">
          {promotions.map((p) => (
            <div key={p.id} className="bg-white rounded-xl shadow-sm p-4 flex items-start gap-4">
              {p.banner_image && (
                <img src={p.banner_image} alt={p.name} className="w-16 h-16 rounded-lg object-cover flex-shrink-0" />
              )}
              <div className="flex-1 min-w-0">
                <p className="font-semibold text-gray-800">{p.name}</p>
                <p className="text-xs text-gray-500 mt-0.5 line-clamp-2">{p.description}</p>
                <div className="flex items-center gap-2 mt-2">
                  <span className="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full">
                    {rewardLabel[p.reward_method] ?? p.reward_method}
                  </span>
                  <span className="text-xs text-gray-400">{formatPromoPeriod(p.start_date, p.end_date, p.start_datetime, p.end_datetime)}</span>
                </div>
              </div>
              <Link href={`/dashboard/claim?promotion_id=${p.id}`}
                className="flex-shrink-0 text-xs bg-blue-700 text-white px-3 py-1.5 rounded-lg hover:bg-blue-800 transition">
                Klaim
              </Link>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
