import { useEffect, useState } from 'react';
import { useOutletContext } from 'react-router-dom';
import { api } from '../api/client';
import Header from '../components/Layout/Header';
import { formatDate, formatPrice } from '../utils/date';

const statusLabels = { pending: 'در انتظار', approved: 'تأیید شده', rejected: 'رد شده' };

export default function PaymentsPage() {
  const { user, setMobileOpen } = useOutletContext();
  const [payments, setPayments] = useState([]);

  useEffect(() => {
    api.get('/payments').then(({ data }) => setPayments(data.payments));
  }, []);

  const uploadReceipt = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const fd = new FormData();
    fd.append('receipt', file);
    await api.post('/payments/receipt', fd, { headers: { 'Content-Type': 'multipart/form-data' } });
    const { data } = await api.get('/payments');
    setPayments(data.payments);
  };

  return (
    <div>
      <Header title="پرداخت‌ها" user={user} onMenuClick={() => setMobileOpen?.(true)} />

      <div className="card mb-6">
        <h3 className="font-bold mb-2">آپلود فیش</h3>
        <p className="text-sm text-gray-500 mb-4">فیش پرداخت خود را آپلود کنید (JPG, PNG, PDF)</p>
        <input type="file" accept=".jpg,.jpeg,.png,.pdf" onChange={uploadReceipt} className="text-sm" />
      </div>

      <div className="space-y-4">
        {payments.length === 0 ? (
          <div className="card text-gray-500 text-center py-8">پرداختی ثبت نشده</div>
        ) : (
          payments.map((p) => (
            <div key={p.id} className="card flex flex-wrap justify-between gap-4">
              <div>
                <p className="font-bold">پکیج {p.planMonths.toLocaleString('fa-IR')} ماهه</p>
                <p className="text-sm text-gray-500">{formatDate(p.createdAt)}</p>
              </div>
              <div className="text-left">
                <p className="text-accent font-bold">{formatPrice(p.finalPrice)} تومان</p>
                {p.discountPercent > 0 && (
                  <p className="text-xs text-emerald-400">تخفیف {p.discountPercent}%</p>
                )}
              </div>
              <span
                className={`px-3 py-1 rounded-lg text-xs self-center ${
                  p.status === 'approved'
                    ? 'bg-emerald-500/20 text-emerald-400'
                    : p.status === 'rejected'
                    ? 'bg-red-500/20 text-red-400'
                    : 'bg-amber-500/20 text-amber-400'
                }`}
              >
                {statusLabels[p.status]}
              </span>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
