'use client';

import { useEffect, useState, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { motion } from 'framer-motion';
import { CreditCard, Loader2, Home, Calendar, Check, X, Clock } from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';
import AuthService from '@/app/services/AuthService';
import { getUserReservations, payDeposit } from '@/app/utils/api';

const STATUS_MAP = ['pending', 'ownerConfirmed', 'depositPaid', 'depositConfirmed', 'completed', 'cancelled'];

const STATUS_CONFIG = {
  pending:          { label: 'قيد الانتظار',      color: 'bg-yellow-100 text-yellow-800 border-yellow-300', depositPaid: false },
  ownerConfirmed:   { label: 'مؤكد من المالك',    color: 'bg-blue-100 text-blue-800 border-blue-300',       depositPaid: false },
  depositPaid:      { label: 'تم دفع السلفة',     color: 'bg-orange-100 text-orange-800 border-orange-300', depositPaid: true },
  depositConfirmed: { label: 'تم تأكيد الدفع',    color: 'bg-green-100 text-green-800 border-green-300',    depositPaid: true },
  completed:        { label: 'منتهي',             color: 'bg-teal-100 text-teal-800 border-teal-300',       depositPaid: true },
  cancelled:        { label: 'ملغي',              color: 'bg-red-100 text-red-800 border-red-300',          depositPaid: false },
};

export default function PaymentsPage() {
  const router = useRouter();
  const [reservations, setReservations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [payingId, setPayingId] = useState(null);

  useEffect(() => {
    // Admin check removed
    // if (AuthService.isAdmin()) {
    //   router.push('/');
    //   return;
    // }
    loadReservations();
  }, [router]);

  const loadReservations = useCallback(async () => {
    try {
      const data = await getUserReservations();
      setReservations(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error(err);
      toast.error('فشل تحميل المدفوعات');
    } finally {
      setLoading(false);
    }
  }, []);

  const handlePayDeposit = async (reservation) => {
    setPayingId(reservation.id);
    try {
      await payDeposit({ reservationId: reservation.id });
      toast.success('تم دفع السلفة بنجاح!');
      loadReservations();
    } catch (err) {
      toast.error(err?.message || 'فشل عملية الدفع');
    } finally {
      setPayingId(null);
    }
  };

  const formatCurrency = (v) => (v ?? 0).toLocaleString() + ' ل.س';

  if (loading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center" dir="rtl">
        <Loader2 className="w-12 h-12 text-amber-500 animate-spin" />
      </div>
    );
  }

  const canPay = (status) => STATUS_MAP[status] === 'pending' || STATUS_MAP[status] === 'ownerConfirmed';

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir="rtl">
      <Toaster position="top-center" reverseOrder={false} />
      <div className="container mx-auto px-4 max-w-4xl">
        <motion.div initial={{ opacity: 0, y: -20 }} animate={{ opacity: 1, y: 0 }} className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">المدفوعات</h1>
          <p className="text-gray-600">إدارة مدفوعات الحجوزات والدفعات المقدمة</p>
        </motion.div>

        {reservations.length === 0 ? (
          <motion.div initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
            className="bg-white rounded-2xl p-12 text-center border-2 border-dashed border-gray-300">
            <CreditCard className="w-16 h-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-xl font-bold text-gray-700 mb-2">لا توجد معاملات مالية</h3>
            <p className="text-gray-500">ستظهر هنا مدفوعاتك للحجوزات</p>
          </motion.div>
        ) : (
          <div className="space-y-4">
            {reservations.map((r, i) => {
              const statusKey = STATUS_MAP[r.status] || 'pending';
              const cfg = STATUS_CONFIG[statusKey];
              const amount = r.depositAmount || r.totalPrice || 0;

              return (
                <motion.div key={r.id || i} initial={{ opacity: 0, y: 20 }} animate={{ opacity: 1, y: 0 }}
                  className="bg-white rounded-2xl shadow-sm border border-gray-200 p-5 hover:shadow-md transition-all">
                  <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                    <div className="flex items-start gap-3">
                      <div className="w-10 h-10 bg-amber-100 rounded-full flex items-center justify-center flex-shrink-0">
                        <Home className="w-5 h-5 text-amber-600" />
                      </div>
                      <div>
                        <h3 className="font-bold text-gray-900">
                          {r.propertyAddress || r._prop?.address || `عقار #${r.propertyId || r.id}`}
                        </h3>
                        <p className="text-sm text-gray-500 mt-1">حجز #{r.id}</p>
                        <div className="flex items-center gap-3 mt-1 text-xs text-gray-400">
                          <span className="flex items-center gap-1"><Calendar className="w-3 h-3" /> {new Date(r.startDate).toLocaleDateString('ar')}</span>
                          <span className="flex items-center gap-1"><Clock className="w-3 h-3" /> {new Date(r.endDate).toLocaleDateString('ar')}</span>
                        </div>
                      </div>
                    </div>
                    <div className="text-right w-full md:w-auto">
                      <div className="text-xl font-bold text-amber-600">{formatCurrency(amount)}</div>
                      <span className={`inline-flex items-center gap-1 px-2 py-1 rounded-lg text-xs font-medium border ${cfg.color}`}>
                        {cfg.depositPaid ? <Check className="w-3 h-3" /> : <X className="w-3 h-3" />}
                        {cfg.label}
                      </span>
                    </div>
                  </div>

                  {canPay(r.status) && (
                    <div className="mt-4 pt-4 border-t border-gray-100 flex justify-end">
                      <button onClick={() => handlePayDeposit(r)} disabled={payingId === r.id}
                        className="flex items-center gap-2 bg-amber-500 hover:bg-amber-600 disabled:bg-amber-300 text-white px-6 py-2.5 rounded-xl text-sm font-medium transition">
                        {payingId === r.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <CreditCard className="w-4 h-4" />}
                        {payingId === r.id ? 'جاري الدفع...' : 'دفع السلفة'}
                      </button>
                    </div>
                  )}
                </motion.div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}