'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { api, apiPaths } from '@/lib/api';
import { useAuthGuard } from '@/lib/useAuthGuard';

type WalletChargeRequestRow = {
  id: number;
  request_number: string;
  amount: number;
  status: string;
  destination_bank?: string;
  bank_name?: string;
  receipt_url?: string | null;
  balance_before?: number | null;
  balance_after?: number | null;
  created_at?: string;
  sender_name?: string;
};

export default function WalletHistoryPage() {
  const { checked, authenticated } = useAuthGuard();
  const [allRecharges, setAllRecharges] = useState<WalletChargeRequestRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('الكل');
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!authenticated) return;
    setLoading(true);
    api
      .get<WalletChargeRequestRow[]>(apiPaths.user.walletChargeRequests)
      .then((res) => {
        if (res.key === 'success') {
          const raw = res.data;
          setAllRecharges(Array.isArray(raw) ? raw : []);
        }
      })
      .finally(() => setLoading(false));
  }, [authenticated]);

  if (!checked) return null;
  if (!authenticated) return null;

  const getStatusLabel = (status?: string) => {
    switch (status) {
      case 'completed':
      case 'approved':
        return 'مكتمل';
      case 'pending':
        return 'بانتظار الموافقة';
      case 'rejected':
        return 'مرفوض';
      default:
        return status || '—';
    }
  };

  const getStatusColor = (status?: string) => {
    switch (status) {
      case 'completed':
      case 'approved':
        return 'bg-green-100 text-green-700';
      case 'pending':
        return 'bg-yellow-100 text-yellow-700';
      case 'rejected':
        return 'bg-red-100 text-red-700';
      default:
        return 'bg-gray-100 text-gray-700';
    }
  };

  const filteredRecharges = allRecharges.filter((r) => {
    const q = searchQuery.trim();
    const matchesSearch =
      !q ||
      String(r.id).includes(q) ||
      (r.request_number || '').includes(q) ||
      (r.sender_name || '').includes(q);
    const label = getStatusLabel(r.status);
    const matchesStatus = statusFilter === 'الكل' || label === statusFilter;
    return matchesSearch && matchesStatus;
  });

  const totalApproved = allRecharges
    .filter((r) => r.status === 'completed' || r.status === 'approved')
    .reduce((sum, r) => sum + Number(r.amount), 0);

  return (
    <div dir="rtl" className="flex flex-col flex-1 bg-gradient-to-br from-blue-50 via-white to-gray-50">
      {previewUrl && (
        <div
          className="fixed inset-0 bg-black/80 z-[60] flex items-center justify-center p-4"
          onClick={() => setPreviewUrl(null)}
        >
          <button
            type="button"
            className="absolute top-6 left-6 w-10 h-10 bg-white rounded-full flex items-center justify-center"
            onClick={() => setPreviewUrl(null)}
          >
            <i className="ri-close-line text-xl"></i>
          </button>
          <img src={previewUrl} alt="" className="max-w-full max-h-[90vh] rounded-lg" />
        </div>
      )}

      <main className="max-w-7xl mx-auto px-6 py-10 flex-1 w-full">
        <div className="flex items-center gap-4 mb-8">
          <Link
            href="/"
            className="w-10 h-10 flex items-center justify-center bg-white border border-gray-200 rounded-lg hover:bg-gray-50 transition-colors cursor-pointer"
          >
            <i className="ri-arrow-right-line text-xl text-gray-700"></i>
          </Link>
          <div>
            <h1 className="text-3xl font-bold text-gray-900">سجل عمليات الشحن</h1>
            <p className="text-gray-500 mt-1">جميع طلبات شحن المحفظة عبر التحويل البنكي</p>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 mb-8">
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 flex items-center justify-center bg-blue-100 rounded-xl">
                <i className="ri-file-list-3-line text-2xl text-blue-600"></i>
              </div>
              <div>
                <p className="text-gray-500 text-sm">إجمالي الطلبات</p>
                <p className="text-2xl font-bold text-gray-900">{allRecharges.length}</p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 flex items-center justify-center bg-green-100 rounded-xl">
                <i className="ri-checkbox-circle-line text-2xl text-green-600"></i>
              </div>
              <div>
                <p className="text-gray-500 text-sm">طلبات مكتملة</p>
                <p className="text-2xl font-bold text-gray-900">
                  {allRecharges.filter((r) => r.status === 'completed' || r.status === 'approved').length}
                </p>
              </div>
            </div>
          </div>
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 flex items-center justify-center bg-purple-100 rounded-xl">
                <i className="ri-wallet-3-line text-2xl text-purple-600"></i>
              </div>
              <div>
                <p className="text-gray-500 text-sm">إجمالي المبالغ المعتمدة</p>
                <p className="text-2xl font-bold text-gray-900">
                  {totalApproved.toLocaleString('ar-SA')} <span className="text-sm text-gray-400">ر.س</span>
                </p>
              </div>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-xl shadow-sm border border-gray-100 p-5 mb-6">
          <div className="flex flex-wrap items-center gap-4">
            <div className="flex-1 min-w-[250px] relative">
              <i className="ri-search-line absolute right-3 top-1/2 -translate-y-1/2 text-gray-400"></i>
              <input
                type="text"
                placeholder="بحث برقم الطلب أو اسم المحوّل..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pr-10 pl-4 py-2.5 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
              />
            </div>
            <div className="flex gap-2 flex-wrap">
              {['الكل', 'مكتمل', 'بانتظار الموافقة', 'مرفوض'].map((s) => (
                <button
                  key={s}
                  type="button"
                  onClick={() => setStatusFilter(s)}
                  className={`px-4 py-2 rounded-full text-sm font-semibold transition-colors cursor-pointer whitespace-nowrap ${
                    statusFilter === s ? 'bg-blue-600 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                  }`}
                >
                  {s}
                </button>
              ))}
            </div>
          </div>
        </div>

        {loading ? (
          <div className="flex justify-center py-16">
            <div className="w-12 h-12 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : (
          <div className="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
            {filteredRecharges.length === 0 ? (
              <div className="p-16 text-center">
                <div className="w-20 h-20 flex items-center justify-center bg-gray-100 rounded-full mx-auto mb-4">
                  <i className="ri-search-line text-3xl text-gray-400"></i>
                </div>
                <h3 className="text-xl font-bold text-gray-900 mb-2">لا توجد نتائج</h3>
                <p className="text-gray-500">لم يتم العثور على عمليات تطابق البحث</p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="w-full min-w-[900px]">
                  <thead className="bg-gray-50 border-b border-gray-100">
                    <tr>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">رقم الطلب</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">التاريخ</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">المبلغ</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">البنك</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">قبل / بعد</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">الإيصال</th>
                      <th className="text-right px-4 py-4 text-sm font-semibold text-gray-700">الحالة</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-100">
                    {filteredRecharges.map((recharge) => (
                      <tr key={recharge.id} className="hover:bg-gray-50 transition-colors">
                        <td className="px-4 py-4">
                          <span className="text-blue-600 font-semibold text-sm">{recharge.request_number}</span>
                        </td>
                        <td className="px-4 py-4 text-sm text-gray-700 whitespace-nowrap">
                          {recharge.created_at ? new Date(recharge.created_at).toLocaleString('ar-SA') : '—'}
                        </td>
                        <td className="px-4 py-4">
                          <span className="text-green-600 font-bold text-sm">
                            +{Number(recharge.amount).toLocaleString('ar-SA')} ر.س
                          </span>
                        </td>
                        <td className="px-4 py-4 text-sm text-gray-700 max-w-[140px]">
                          {recharge.destination_bank || recharge.bank_name || '—'}
                        </td>
                        <td className="px-4 py-4 text-xs text-gray-600 whitespace-nowrap">
                          {(recharge.status === 'completed' || recharge.status === 'approved') &&
                          recharge.balance_before != null &&
                          recharge.balance_after != null ? (
                            <>
                              {recharge.balance_before.toLocaleString('ar-SA')} ←{' '}
                              {recharge.balance_after.toLocaleString('ar-SA')}
                            </>
                          ) : (
                            '—'
                          )}
                        </td>
                        <td className="px-4 py-4">
                          {recharge.receipt_url ? (
                            <button
                              type="button"
                              onClick={() => setPreviewUrl(recharge.receipt_url!)}
                              className="text-blue-600 text-sm font-semibold hover:underline"
                            >
                              عرض
                            </button>
                          ) : (
                            <span className="text-gray-400 text-sm">—</span>
                          )}
                        </td>
                        <td className="px-4 py-4">
                          <span
                            className={`px-3 py-1 rounded-full text-xs font-semibold ${getStatusColor(
                              recharge.status,
                            )}`}
                          >
                            {getStatusLabel(recharge.status)}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </div>
        )}
      </main>
    </div>
  );
}
