"use client";

import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { motion } from 'framer-motion';
import { useTranslation } from 'react-i18next';
import {
  Home,
  MapPin,
  Phone,
  ShieldCheck,
  CreditCard,
  Banknote,
  Building,
  ArrowLeftRight,
  Loader2,
  Check,
  X,
  Calendar,
  Clock,
  LogIn,
  Lock,
  Info,
  Landmark,
  Wallet,
} from 'lucide-react';
import toast, { Toaster } from 'react-hot-toast';
import AuthService from '@/app/services/AuthService';
import { payDeposit, getMyTransaction, getPaymentTypes } from '@/app/utils/api';

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

function getStatusConfig(t) {
  return {
    pending:          { label: t('bookingStatus.pending'),          color: 'bg-yellow-100 text-yellow-800 border-yellow-300', icon: Clock },
    ownerConfirmed:   { label: t('bookingStatus.ownerConfirmed'),   color: 'bg-blue-100 text-blue-800 border-blue-300',       icon: ShieldCheck },
    depositPaid:      { label: t('bookingStatus.depositPaid'),      color: 'bg-orange-100 text-orange-800 border-orange-300', icon: Wallet },
    depositConfirmed: { label: t('bookingStatus.depositConfirmed'), color: 'bg-green-100 text-green-800 border-green-300',    icon: Check },
    completed:        { label: t('bookingStatus.completed'),        color: 'bg-teal-100 text-teal-800 border-teal-300',       icon: Check },
    cancelled:        { label: t('bookingStatus.cancelled'),        color: 'bg-red-100 text-red-800 border-red-300',          icon: X },
  };
}

function getPaymentMethods(t) {
  return [
    { id: 'cash',       label: t('payments.method.cash'),       desc: t('payments.method.cashDesc'),       icon: Banknote,       active: true },
    { id: 'office',     label: t('payments.method.office'),     desc: t('payments.method.officeDesc'),     icon: Building,       active: true },
    { id: 'transfer',   label: t('payments.method.transfer'),   desc: t('payments.method.transferDesc'),   icon: ArrowLeftRight, active: false },
    { id: 'electronic', label: t('payments.method.electronic'), desc: t('payments.method.electronicDesc'), icon: CreditCard,     active: false },
  ];
}

function formatCurrency(v, sign = '') {
  return `${sign} ${Number(v ?? 0).toLocaleString()}`;
}

function formatDate(date) {
  if (!date) return '';
  const d = new Date(date);
  if (Number.isNaN(d.getTime())) return '';
  return d.toLocaleDateString('en-GB');
}

function normalizeText(value) {
  return String(value ?? '').trim().toLowerCase();
}

function isHaramText(value) {
  const text = normalizeText(value);
  return text.includes('haram') || text.includes('هرم');
}

export default function PaymentsPage() {
  const { t, i18n } = useTranslation();
  const [reservations, setReservations] = useState([]);
  const [loading, setLoading] = useState(true);
  const [payingId, setPayingId] = useState(null);
  const [isGuest, setIsGuest] = useState(null);
  const [paymentMethods, setPaymentMethods] = useState([]);
  const [loadingPaymentMethods, setLoadingPaymentMethods] = useState(true);
  const [selectedPayment, setSelectedPayment] = useState(null);

  const loadReservations = useCallback(async () => {
    try {
      const json = await getMyTransaction();
      const items = Array.isArray(json) ? json : [];

      const mapped = items.map((item) => {
        const deposit = item?.diposit || item?.deposit || {};
        const reservation = deposit?.reservation || {};
        const transaction = deposit?.transaction || {};
        const currency = item?.currency || {};
        const propertyInfo = reservation?.propertyInformation || {};

        return {
          id: deposit.id ?? reservation.id ?? item?.id,
          reservationId: reservation.id ?? deposit.reservationId ?? item?.reservationId,
          status: reservation.status ?? 0,
          startDate: reservation.startDate,
          endDate: reservation.endDate,
          totalPrice: reservation.totalPrice ?? transaction.amount ?? 0,
          depositAmount: transaction.amount ?? reservation.totalPrice ?? 0,
          currencySign: currency.sign || t('currency.syp'),
          currencyName: currency.name || '',
          currencyRate: currency.rate,
          propertyName: propertyInfo.name || propertyInfo.address || reservation.propertyName || `${t('payments.propertyLabel')} #${reservation.id || ''}`,
          propertyAddress: propertyInfo.address || reservation.propertyAddress || '',
          propertyCity: propertyInfo.city || reservation.city || '',
          _deposit: deposit,
          _reservation: reservation,
        };
      });

      setReservations(mapped);
    } catch (err) {
      console.error(err);
      toast.error(t('payments.loadingTransactions'));
    } finally {
      setLoading(false);
    }
  }, [t]);

  const loadPaymentMethods = useCallback(async () => {
    setLoadingPaymentMethods(true);
    try {
      const data = await getPaymentTypes();
      const methods = Array.isArray(data) ? data : [];
      setPaymentMethods(methods);

      const firstActive = methods.find((method) => method?.isActive === true || method?.active === true);
      if (firstActive) {
        setSelectedPayment(firstActive.name ?? firstActive.id ?? null);
      }
    } catch (err) {
      console.error('[Payments] failed to load payment methods', err);
      setPaymentMethods([]);
    } finally {
      setLoadingPaymentMethods(false);
    }
  }, []);

  useEffect(() => {
    if (AuthService.isGuest()) {
      setIsGuest(true);
      setLoading(false);
      return;
    }
    setIsGuest(false);
    loadReservations();
  }, [loadReservations]);

  useEffect(() => {
    loadPaymentMethods();
  }, [loadPaymentMethods]);

  const resolvePaymentTypeId = (paymentKey) => {
    const method = paymentMethods.find(
      (m) => String(m.id) === String(paymentKey) || String(m.name) === String(paymentKey),
    );
    return method?.id ?? paymentKey;
  };

  const handlePayDeposit = async (reservation, paymentKey, paymentImageFile) => {
    const paymentTypeId = resolvePaymentTypeId(paymentKey);
    const selectedMethod = paymentMethods.find(
      (m) => String(m.id) === String(paymentTypeId) || String(m.name) === String(paymentTypeId),
    );

    const isHaram =
      isHaramText(selectedMethod?.name) ||
      isHaramText(selectedMethod?.label) ||
      isHaramText(selectedMethod?.id) ||
      isHaramText(paymentKey);

    setPayingId(reservation.id);
    try {
      await payDeposit({
        reservationId: reservation.id,
        paymentTypeId,
        paymentImage: paymentImageFile,
      });
      toast.success(t('payments.depositPaidSuccess'));
      loadReservations();
    } catch (err) {
      toast.error(err?.message || t('payments.paymentFailed'));
    } finally {
      setPayingId(null);
    }
  };

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

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

  if (isGuest) {
    return (
      <div className="min-h-screen bg-gradient-to-b from-amber-50/50 to-white flex items-center justify-center p-4" dir={i18n.dir()}>
        <motion.div
          initial={{ opacity: 0, scale: 0.95 }}
          animate={{ opacity: 1, scale: 1 }}
          className="bg-white rounded-3xl shadow-xl border border-gray-200 p-10 max-w-md w-full text-center"
        >
          <div className="w-20 h-20 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-6">
            <Lock className="w-10 h-10 text-amber-600" />
          </div>
          <h2 className="text-2xl font-bold text-gray-900 mb-3">{t('payments.title')}</h2>
          <p className="text-gray-600 leading-relaxed mb-8">
            {t('payments.loginRequiredDesc')}
          </p>
          <Link
            href="/login"
            className="inline-flex items-center gap-2 bg-amber-500 hover:bg-amber-600 text-white px-8 py-3 rounded-2xl text-lg font-semibold transition shadow-lg shadow-amber-200"
          >
            <LogIn className="w-5 h-5" />
            {t('login')}
          </Link>
        </motion.div>
      </div>
    );
  }

  const payables = reservations.filter((r) => canPay(r.status));
  const others = reservations.filter((r) => !canPay(r.status));

  return (
    <div className="min-h-screen bg-gray-50 py-8" dir={i18n.dir()}>
      <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">{t('payments.title')}</h1>
          <p className="text-gray-600">{t('payments.description')}</p>
        </motion.div>

        {payables.length > 0 && (
          <div className="space-y-6 mb-10">
            <h2 className="text-xl font-bold text-gray-800 flex items-center gap-2">
              <Wallet className="w-5 h-5 text-amber-500" />
              {t('payments.payablesTitle')}
            </h2>
            {payables.map((r, i) => (
              <PaymentCard
                key={r.id || i}
                reservation={r}
                payingId={payingId}
                paymentMethods={paymentMethods}
                loadingPaymentMethods={loadingPaymentMethods}
                selectedPayment={selectedPayment}
                onSelectPayment={setSelectedPayment}
                onPay={handlePayDeposit}
              />
            ))}
          </div>
        )}

        {others.length > 0 && (
          <div className="space-y-4">
            <h2 className="text-xl font-bold text-gray-800 flex items-center gap-2">
              <Clock className="w-5 h-5 text-gray-500" />
              {t('payments.previousReservationsTitle')}
            </h2>
            {others.map((r, i) => {
              const statusKey = STATUS_MAP[r.status] || 'pending';
              const cfg = getStatusConfig(t)[statusKey];
              const Icon = cfg.icon;
              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"
                >
                  <div className="flex items-center justify-between gap-3 mb-3">
                    <span className="text-sm font-medium text-gray-400">#{r.reservationId || r.id}</span>
                    <span className={`inline-flex items-center gap-1 px-3 py-1 rounded-full text-xs font-medium border ${cfg.color}`}>
                      <Icon className="w-3 h-3" />
                      {cfg.label}
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-2 text-sm text-gray-600">
                      <Calendar className="w-4 h-4" />
                      {formatDate(r.startDate)} - {formatDate(r.endDate)}
                    </div>
                    <div className="text-lg font-bold text-gray-900">
                      {formatCurrency(amount, r.currencySign)}
                    </div>
                  </div>
                </motion.div>
              );
            })}
          </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">{t('payments.noTransactions')}</h3>
            <p className="text-gray-500">{t('payments.noTransactionsDesc')}</p>
          </motion.div>
        )}
      </div>
    </div>
  );
}

// eslint-disable-next-line react/prop-types
function PaymentCard({ reservation, payingId, paymentMethods, loadingPaymentMethods, selectedPayment, onSelectPayment, onPay }) {
  const { t } = useTranslation();
  const r = reservation;
  const amount = r.depositAmount || r.totalPrice || 0;
  const [showCashDialog, setShowCashDialog] = useState(false);
  const [localPaymentImage, setLocalPaymentImage] = useState(null);

  const methods = paymentMethods.length > 0 ? paymentMethods : getPaymentMethods(t);

  const selectedMethod = methods.find((m) => {
    const methodName = normalizeText(m?.name);
    const methodLabel = normalizeText(m?.label);
    const methodId = normalizeText(m?.id);
    const paymentKey = normalizeText(selectedPayment);

    return methodName === paymentKey || methodLabel === paymentKey || methodId === paymentKey;
  });

  const isHaramPayment =
    isHaramText(selectedPayment) ||
    isHaramText(selectedMethod?.name) ||
    isHaramText(selectedMethod?.label) ||
    isHaramText(selectedMethod?.id);

  return (
    <>
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="bg-white rounded-3xl shadow-md border border-gray-200 overflow-hidden"
      >
        {/* Property details */}
        <div className="p-6 border-b border-gray-100">
          <div className="flex items-start gap-4 mb-4">
            <div className="w-14 h-14 bg-amber-100 rounded-2xl flex items-center justify-center shrink-0">
              <Home className="w-7 h-7 text-amber-600" />
            </div>
            <div className="min-w-0 flex-1">
              <h3 className="text-xl font-bold text-gray-900 mb-1">
                {r.propertyName}
              </h3>
              {(r.propertyAddress || r.propertyCity) && (
                <p className="text-sm text-gray-500 flex items-center gap-1">
                  <MapPin className="w-3.5 h-3.5" />
                  {[r.propertyCity, r.propertyAddress].filter(Boolean).join(' - ')}
                </p>
              )}
            </div>
          </div>

          <div className="flex items-center gap-4 text-sm text-gray-600">
            <span className="flex items-center gap-1.5">
              <Calendar className="w-4 h-4 text-gray-400" />
              {formatDate(r.startDate)} - {formatDate(r.endDate)}
            </span>
            <span className="flex items-center gap-1.5">
              <Clock className="w-4 h-4 text-gray-400" />
              #{r.reservationId || r.id}
            </span>
          </div>
        </div>

        {/* Deposit amount */}
        <div className="px-6 py-5 border-b border-gray-100">
          <div className="text-center">
            <p className="text-sm text-gray-500 mb-1">{t('payments.depositAmount')}</p>
            <p className="text-4xl font-bold text-amber-600">
              {formatCurrency(amount, r.currencySign)}
            </p>
            <p className="text-xs text-gray-400 mt-2">
              {t('payments.depositPaidToPlatform')}
            </p>
          </div>
        </div>

        {/* Payment methods note */}
        <div className="px-6 py-4 bg-amber-50 border-b border-amber-100">
          <div className="flex items-start gap-3">
            <Info className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
            <p className="text-sm text-amber-800 leading-relaxed">
              {t('payments.cashOnlyNotice')}
            </p>
          </div>
        </div>

        {/* Payment method options */}
        <div className="px-6 py-5 border-b border-gray-100">
          <p className="text-sm font-bold text-gray-700 mb-3">{t('payments.paymentMethodLabel')}</p>
          <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
            {loadingPaymentMethods ? (
              <div className="col-span-full rounded-2xl border border-dashed border-gray-200 bg-gray-50 p-4 text-sm text-gray-600">
                {t('payments.loadingPaymentMethods')}
              </div>
            ) : methods.length === 0 ? (
              <div className="col-span-full rounded-2xl border border-dashed border-gray-200 bg-gray-50 p-4 text-sm text-gray-600">
                {t('payments.noPaymentMethodsAvailable')}
              </div>
            ) : (
              methods.map((method, index) => {
                const optionId = method.name ?? method.id ?? `payment-method-${index}`;
                const isActive = method?.isActive === true || method?.active === true;
                const isSelected = String(selectedPayment) === String(optionId);
                const Icon = method.icon || CreditCard;

                return (
                  <button
                    key={optionId}
                    type="button"
                    disabled={!isActive}
                    onClick={() => isActive && onSelectPayment(optionId)}
                    className={`relative flex items-start gap-3 p-4 rounded-2xl border-2 text-right transition-all ${
                      !isActive
                        ? 'border-gray-100 bg-gray-50 opacity-50 cursor-not-allowed'
                        : isSelected
                          ? 'border-amber-500 bg-amber-50 shadow-sm'
                          : 'border-gray-200 bg-white hover:border-amber-300 cursor-pointer'
                    }`}
                  >
                    <div
                      className={`w-10 h-10 rounded-xl flex items-center justify-center shrink-0 ${
                        isSelected ? 'bg-amber-500 text-white' : 'bg-gray-100 text-gray-500'
                      }`}
                    >
                      <Icon className="w-5 h-5" />
                    </div>
                    <div className="min-w-0 flex-1">
                      <p className={`text-sm font-bold ${isSelected ? 'text-amber-900' : 'text-gray-800'}`}>
                        {method.name || method.label || t('payments.paymentMethodName')}
                      </p>
                      {method.description && (
                        <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">
                          {method.description}
                        </p>
                      )}
                      <span
                        className={`inline-block mt-1 text-[10px] font-medium px-2 py-0.5 rounded-full ${
                          isActive ? 'bg-amber-100 text-amber-700' : 'bg-gray-200 text-gray-500'
                        }`}
                      >
                        {isActive ? t('payments.methodActive') : t('payments.methodInactive')}
                      </span>
                    </div>
                    {isSelected && (
                      <div className="absolute top-2 left-2 w-5 h-5 bg-amber-500 rounded-full flex items-center justify-center">
                        <Check className="w-3 h-3 text-white" />
                      </div>
                    )}
                  </button>
                );
              })
            )}
          </div>
        </div>

        {/* Upload receipt only for Haram */}
        {isHaramPayment && (
          <div className="px-6 py-5 border-b border-gray-100">
            <label className="block text-sm font-bold text-gray-700 mb-3">
              {t('payments.uploadReceipt')}
            </label>
            <input
              type="file"
              accept="image/*"
              onChange={(e) => setLocalPaymentImage(e.target.files?.[0] || null)}
              className="block w-full rounded-2xl border border-gray-300 bg-white px-4 py-3 text-sm text-gray-700 file:mr-4 file:rounded-xl file:border-0 file:bg-amber-500 file:px-4 file:py-2 file:text-white hover:file:bg-amber-600"
            />
          </div>
        )}

        {/* Pay button */}
        <div className="px-6 py-5 border-b border-gray-100">
          <motion.button
            type="button"
            onClick={() => onPay(r, selectedPayment, localPaymentImage)}
            disabled={payingId === r.id}
            whileHover={{ scale: 1.01 }}
            whileTap={{ scale: 0.99 }}
            className="w-full bg-amber-500 hover:bg-amber-600 disabled:bg-amber-300 text-white font-bold py-4 px-6 rounded-2xl text-lg transition-all shadow-lg hover:shadow-xl flex items-center justify-center gap-3"
          >
            {payingId === r.id ? (
              <>
                <Loader2 className="w-5 h-5 animate-spin" />
                {t('payments.processingPayment')}
              </>
            ) : (
              <>
                <Banknote className="w-5 h-5" />
                {t('payments.payButton', { amount: formatCurrency(amount, r.currencySign) })}
              </>
            )}
          </motion.button>
        </div>

        {/* Cash pay button */}
        <div className="px-6 py-4 border-b border-gray-100">
          <button
            type="button"
            onClick={() => setShowCashDialog(true)}
            className="w-full bg-white border-2 border-amber-200 hover:border-amber-400 text-amber-700 font-bold py-3 px-6 rounded-2xl text-base transition-all flex items-center justify-center gap-2"
          >
            <Building className="w-5 h-5" />
            {t('payments.payCashButton')}
          </button>
        </div>

        {/* Cash payment dialog */}
        {showCashDialog && (
          <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 px-4 py-8">
            <motion.div
              initial={{ opacity: 0, scale: 0.95 }}
              animate={{ opacity: 1, scale: 1 }}
              className="w-full max-w-md rounded-3xl bg-white p-8 shadow-2xl border border-gray-200 text-center"
            >
              <div className="w-16 h-16 bg-amber-100 rounded-full flex items-center justify-center mx-auto mb-5">
                <Clock className="w-8 h-8 text-amber-600" />
              </div>
              <h3 className="text-xl font-bold text-gray-900 mb-3">{t('payments.cashPendingDialogTitle')}</h3>
              <p className="text-gray-600 leading-relaxed mb-6">
                {t('payments.cashPendingDialogDesc1')}
                <br />
                {t('payments.cashPendingDialogDesc2')}
              </p>
              <div className="bg-gray-50 rounded-2xl p-4 mb-6 text-right">
                <p className="text-sm font-bold text-gray-800 mb-1">{t('payments.platformOfficeLabel')}</p>
                <p className="text-sm text-gray-600">{t('payments.platformOfficeFullAddress')}</p>
                <p className="text-sm text-gray-600 flex items-center gap-1 mt-1" dir="ltr">
                  <Phone className="w-3.5 h-3.5" />
                  +963567823411
                </p>
              </div>
              <div className="flex flex-col gap-3 sm:flex-row">
                <button
                  type="button"
                  onClick={() => setShowCashDialog(false)}
                  className="w-full px-5 py-3 rounded-xl border border-gray-300 text-gray-700 hover:bg-gray-100 transition-colors font-medium"
                >
                  {t('payments.closeButton')}
                </button>
                <Link
                  href="/reservations"
                  className="w-full px-5 py-3 rounded-xl bg-amber-500 text-white font-semibold text-center hover:bg-amber-600 transition-colors"
                >
                  {t('payments.myReservationsLink')}
                </Link>
              </div>
            </motion.div>
          </div>
        )}

        {/* Platform location */}
        <div className="px-6 py-5 bg-gray-50">
          <div className="flex items-start gap-3">
            <Landmark className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
            <div>
              <p className="text-sm font-bold text-gray-800 mb-1">{t('payments.cashPaymentLocationLabel')}</p>
              <p className="text-sm text-gray-600 leading-relaxed">
                {t('payments.platformOfficeFullAddress')}
              </p>
              <p className="text-sm text-gray-600 flex items-center gap-1 mt-1">
                <Phone className="w-3.5 h-3.5" />
                <span dir="ltr">+963567823411</span>
              </p>
            </div>
          </div>
        </div>
      </motion.div>
    </>
  );
}