'use client';

import { useEffect, useState, useCallback } from 'react';
import api from '@/lib/axios';
import { Gift, Star, AlertCircle, CheckCircle2, Package, TrendingUp, TrendingDown, RefreshCw } from 'lucide-react';
import { formatTimestamp, formatDate } from '@/lib/dateUtils';

interface RewardItem {
  id: number;
  name: string;
  point_cost: number;
  image_url: string | null;
}

interface MyItem {
  id: number;
  item_name: string;
  image_url: string | null;
  points_used: number;
  status: 'open' | 'closed';
  redeemed_at: string;
}

interface PointTx {
  id: number;
  type: 'earned' | 'redeemed' | 'expired' | 'adjusted';
  points: number;
  description: string;
  balance_before: number;
  balance_after: number;
  created_at: string;
}

const txTypeConfig: Record<string, { label: string; icon: React.ReactNode; color: string }> = {
  earned:   { label: 'Poin Masuk',   icon: <TrendingUp className="w-4 h-4" />,   color: 'text-green-600' },
  redeemed: { label: 'Poin Keluar',  icon: <TrendingDown className="w-4 h-4" />, color: 'text-red-500' },
  expired:  { label: 'Kadaluarsa',   icon: <TrendingDown className="w-4 h-4" />, color: 'text-gray-400' },
  adjusted: { label: 'Penyesuaian',  icon: <RefreshCw className="w-4 h-4" />,    color: 'text-blue-500' },
};

export default function RedeemPage() {
  const [items, setItems]           = useState<RewardItem[]>([]);
  const [myItems, setMyItems]       = useState<MyItem[]>([]);
  const [userPoints, setUserPoints] = useState<number>(0);
  const [loading, setLoading]       = useState(true);
  const [redeeming, setRedeeming]   = useState<number | null>(null);
  const [toast, setToast]           = useState<{ type: 'success' | 'error'; msg: string } | null>(null);
  const [tab, setTab]               = useState<'catalog' | 'my-items' | 'history'>('catalog');

  // Point history state
  const [pointHistory, setPointHistory]       = useState<PointTx[]>([]);
  const [historyLoading, setHistoryLoading]   = useState(false);
  const [historyPage, setHistoryPage]         = useState(1);
  const [historyLastPage, setHistoryLastPage] = useState(1);

  const showToast = (type: 'success' | 'error', msg: string) => {
    setToast({ type, msg });
    setTimeout(() => setToast(null), 4000);
  };

  const loadData = () => {
    Promise.all([
      api.get('/end-user/reward-items'),
      api.get('/end-user/reward-items/my-items'),
      api.get('/end-user/profile'),
    ]).then(([itemsRes, myItemsRes, profileRes]) => {
      setItems(itemsRes.data.data ?? []);
      setMyItems(myItemsRes.data.data ?? []);
      setUserPoints(profileRes.data.data?.total_points ?? 0);
    }).catch(() => {})
      .finally(() => setLoading(false));
  };

  const loadHistory = useCallback((page: number) => {
    setHistoryLoading(true);
    api.get(`/end-user/points/history?page=${page}`)
      .then((r) => {
        setPointHistory(r.data.data ?? []);
        setHistoryPage(r.data.meta?.current_page ?? 1);
        setHistoryLastPage(r.data.meta?.last_page ?? 1);
        setUserPoints(r.data.current_balance ?? userPoints);
      })
      .catch(() => {})
      .finally(() => setHistoryLoading(false));
  }, []);

  useEffect(() => { loadData(); }, []);
  useEffect(() => { if (tab === 'history') loadHistory(1); }, [tab]);

  const [confirm, setConfirm] = useState<RewardItem | null>(null);

  const handleRedeem = async (item: RewardItem) => {
    if (userPoints < item.point_cost) {
      showToast('error', `Poin tidak mencukupi. Poin Anda: ${userPoints.toLocaleString('id-ID')}, dibutuhkan: ${item.point_cost.toLocaleString('id-ID')}`);
      return;
    }
    // Show confirmation first
    setConfirm(item);
  };

  const doRedeem = async (item: RewardItem) => {
    setConfirm(null);
    setRedeeming(item.id);
    try {
      const res = await api.post('/end-user/reward-items/redeem', { reward_item_id: item.id });
      setUserPoints(res.data.data?.points_balance ?? userPoints - item.point_cost);
      showToast('success', res.data.message ?? `Berhasil menukar poin dengan ${item.name}`);
      api.get('/end-user/reward-items/my-items').then(r => setMyItems(r.data.data ?? []));
    } catch (e: any) {
      const code = e.response?.data?.code;
      if (code === 'INSUFFICIENT_POINTS') {
        showToast('error', 'Poin tidak mencukupi.');
      } else {
        showToast('error', e.response?.data?.message ?? 'Gagal menukar poin.');
      }
    } finally {
      setRedeeming(null);
    }
  };

  return (
    <div>
      {/* Confirmation Modal */}
      {confirm && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 px-4">
          <div className="bg-white rounded-2xl shadow-xl p-6 max-w-sm w-full">
            <h2 className="text-base font-bold text-gray-800 mb-2">Konfirmasi Penukaran</h2>
            <p className="text-sm text-gray-600 mb-1">
              Tukar <strong>{confirm.point_cost.toLocaleString('id-ID')} poin</strong> dengan:
            </p>
            <p className="text-sm font-semibold text-blue-700 mb-4">{confirm.name}</p>
            <p className="text-xs text-gray-400 mb-5">
              Sisa poin setelah penukaran: <strong>{(userPoints - confirm.point_cost).toLocaleString('id-ID')}</strong>
            </p>
            <div className="flex gap-3">
              <button
                onClick={() => doRedeem(confirm)}
                className="flex-1 bg-blue-700 text-white py-2 rounded-lg text-sm font-medium hover:bg-blue-800">
                Ya, Tukar
              </button>
              <button
                onClick={() => setConfirm(null)}
                className="flex-1 bg-gray-100 text-gray-700 py-2 rounded-lg text-sm font-medium hover:bg-gray-200">
                Batal
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Toast */}
      {toast && (
        <div className={`fixed top-4 right-4 z-50 flex items-center gap-2 px-4 py-3 rounded-xl shadow-lg text-sm font-medium
          ${toast.type === 'success' ? 'bg-green-50 text-green-700 border border-green-200' : 'bg-red-50 text-red-700 border border-red-200'}`}>
          {toast.type === 'success'
            ? <CheckCircle2 className="w-4 h-4 flex-shrink-0" />
            : <AlertCircle className="w-4 h-4 flex-shrink-0" />}
          {toast.msg}
        </div>
      )}

      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <h1 className="text-xl font-bold text-gray-800">Tukar Poin</h1>
        <div className="flex items-center gap-1.5 bg-blue-50 text-blue-700 px-3 py-1.5 rounded-full text-sm font-semibold">
          <Star className="w-4 h-4 fill-blue-400 text-blue-400" />
          {userPoints.toLocaleString('id-ID')} poin
        </div>
      </div>

      {/* Tabs */}
      <div className="flex gap-2 mb-5 border-b">
        <button
          onClick={() => setTab('catalog')}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition ${tab === 'catalog' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'}`}>
          Katalog Item
        </button>
        <button
          onClick={() => setTab('my-items')}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition ${tab === 'my-items' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'}`}>
          Item Saya {myItems.length > 0 && <span className="ml-1 bg-blue-100 text-blue-600 text-xs px-1.5 py-0.5 rounded-full">{myItems.length}</span>}
        </button>
        <button
          onClick={() => setTab('history')}
          className={`pb-2 px-1 text-sm font-medium border-b-2 transition ${tab === 'history' ? 'border-blue-600 text-blue-600' : 'border-transparent text-gray-500'}`}>
          Mutasi Poin
        </button>
      </div>

      {loading ? (
        <div className="space-y-3">
          {[1,2,3].map(i => <div key={i} className="bg-white rounded-xl p-4 animate-pulse h-20" />)}
        </div>
      ) : tab === 'catalog' ? (
        items.length === 0 ? (
          <div className="text-center py-16 text-gray-400">
            <Gift className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p>Tidak ada item yang tersedia saat ini.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {items.map((item) => {
              const canAfford = userPoints >= item.point_cost;
              const isLoading = redeeming === item.id;
              return (
                <div key={item.id} className="bg-white rounded-xl shadow-sm p-4 flex items-center gap-4">
                  {item.image_url ? (
                    <img src={item.image_url} alt={item.name}
                      className="w-14 h-14 rounded-lg object-cover flex-shrink-0" />
                  ) : (
                    <div className="w-14 h-14 rounded-lg bg-blue-50 flex items-center justify-center flex-shrink-0">
                      <Gift className="w-6 h-6 text-blue-400" />
                    </div>
                  )}
                  <div className="flex-1 min-w-0">
                    <p className="font-medium text-gray-800">{item.name}</p>
                    <p className={`text-xs font-semibold mt-0.5 ${canAfford ? 'text-blue-600' : 'text-red-400'}`}>
                      {item.point_cost.toLocaleString('id-ID')} poin
                    </p>
                  </div>
                  <button
                    onClick={() => handleRedeem(item)}
                    disabled={!canAfford || isLoading}
                    className={`flex-shrink-0 px-4 py-2 rounded-lg text-sm font-semibold transition
                      ${canAfford && !isLoading
                        ? 'bg-blue-600 text-white hover:bg-blue-700'
                        : 'bg-gray-100 text-gray-400 cursor-not-allowed'}`}>
                    {isLoading ? '...' : 'Tukar'}
                  </button>
                </div>
              );
            })}
          </div>
        )
      ) : (
        myItems.length === 0 ? (
          <div className="text-center py-16 text-gray-400">
            <Package className="w-12 h-12 mx-auto mb-3 opacity-30" />
            <p>Belum ada item yang ditukar.</p>
          </div>
        ) : (
          <div className="space-y-3">
            {myItems.map((item) => (
              <div key={item.id} className="bg-white rounded-xl shadow-sm p-4 flex items-center gap-4">
                {item.image_url ? (
                  <img src={item.image_url} alt={item.item_name ?? ''}
                    className="w-12 h-12 rounded-lg object-cover flex-shrink-0" />
                ) : (
                  <div className="w-12 h-12 rounded-lg bg-gray-100 flex items-center justify-center flex-shrink-0">
                    <Package className="w-5 h-5 text-gray-400" />
                  </div>
                )}
                <div className="flex-1 min-w-0">
                  <p className="font-medium text-gray-800">{item.item_name}</p>
                  <p className="text-xs text-gray-500 mt-0.5">
                    {item.points_used.toLocaleString('id-ID')} poin &bull; {formatDate(item.redeemed_at)}
                  </p>
                </div>
                <span className={`flex-shrink-0 text-xs font-semibold px-2.5 py-1 rounded-full
                  ${item.status === 'open' ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'}`}>
                  {item.status === 'open' ? 'Open' : 'Closed'}
                </span>
              </div>
            ))}
          </div>
        )
      )}

      {/* History Tab */}
      {tab === 'history' && (
        <div>
          {/* Summary card */}
          <div className="bg-blue-50 border border-blue-100 rounded-xl px-4 py-3 mb-4 flex items-center justify-between">
            <span className="text-sm text-blue-700">Saldo Poin Saat Ini</span>
            <span className="text-lg font-bold text-blue-700">{userPoints.toLocaleString('id-ID')} poin</span>
          </div>

          {historyLoading ? (
            <div className="space-y-3">
              {[1,2,3].map(i => <div key={i} className="bg-white rounded-xl p-4 animate-pulse h-20" />)}
            </div>
          ) : pointHistory.length === 0 ? (
            <div className="text-center py-16 text-gray-400">
              <RefreshCw className="w-10 h-10 mx-auto mb-3 opacity-30" />
              <p className="text-sm">Belum ada mutasi poin.</p>
            </div>
          ) : (
            <>
              <div className="space-y-2">
                {pointHistory.map((tx) => {
                  const cfg = txTypeConfig[tx.type] ?? txTypeConfig.adjusted;
                  const isPositive = tx.points > 0;
                  return (
                    <div key={tx.id} className="bg-white rounded-xl shadow-sm p-4">
                      <div className="flex items-start justify-between gap-3">
                        <div className={`flex-shrink-0 mt-0.5 ${cfg.color}`}>{cfg.icon}</div>
                        <div className="flex-1 min-w-0">
                          <p className="text-sm font-medium text-gray-800">{tx.description || cfg.label}</p>
                          <p className="text-xs text-gray-400 mt-0.5">{formatTimestamp(tx.created_at)}</p>
                        </div>
                        <div className="text-right flex-shrink-0">
                          <p className={`text-sm font-bold ${isPositive ? 'text-green-600' : 'text-red-500'}`}>
                            {isPositive ? '+' : ''}{tx.points.toLocaleString('id-ID')}
                          </p>
                          <span className={`text-xs px-2 py-0.5 rounded-full font-medium ${
                            tx.type === 'earned' ? 'bg-green-100 text-green-700' :
                            tx.type === 'redeemed' ? 'bg-red-100 text-red-600' :
                            tx.type === 'expired' ? 'bg-gray-100 text-gray-500' :
                            'bg-blue-100 text-blue-600'
                          }`}>{cfg.label}</span>
                        </div>
                      </div>
                      {/* Saldo before/after */}
                      <div className="flex justify-between mt-2 pt-2 border-t border-gray-50 text-xs text-gray-400">
                        <span>Saldo awal: <strong className="text-gray-600">{tx.balance_before.toLocaleString('id-ID')}</strong></span>
                        <span>Saldo akhir: <strong className="text-gray-600">{tx.balance_after.toLocaleString('id-ID')}</strong></span>
                      </div>
                    </div>
                  );
                })}
              </div>

              {historyLastPage > 1 && (
                <div className="flex justify-center gap-2 mt-4">
                  <button onClick={() => { setHistoryPage(p => p - 1); loadHistory(historyPage - 1); }}
                    disabled={historyPage <= 1}
                    className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">
                    ← Sebelumnya
                  </button>
                  <span className="px-3 py-1.5 text-sm text-gray-500">{historyPage} / {historyLastPage}</span>
                  <button onClick={() => { setHistoryPage(p => p + 1); loadHistory(historyPage + 1); }}
                    disabled={historyPage >= historyLastPage}
                    className="px-3 py-1.5 text-sm border rounded-lg disabled:opacity-40 hover:bg-gray-50">
                    Berikutnya →
                  </button>
                </div>
              )}
            </>
          )}
        </div>
      )}
    </div>
  );
}
