import { useEffect, useState } from 'react';
import { useParams } from 'react-router-dom';
import { paymentsAPI } from '../services/api';

function formatInstallment(installment) {
  return Number(installment || 0) > 0 ? `Installment ${installment}` : 'One-time payment';
}

export default function PaymentDetail() {
  const { id } = useParams();
  const [payment, setPayment] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchPayment = async () => {
      try {
        const response = await paymentsAPI.get(id);
        setPayment(response);
      } catch (fetchError) {
        setError(fetchError.response?.data?.error || 'Failed to load payment details.');
      } finally {
        setLoading(false);
      }
    };

    fetchPayment();
  }, [id]);

  if (loading) {
    return <p className="text-gray-600">Loading...</p>;
  }

  if (error) {
    return <div className="rounded-2xl border border-red-200 bg-red-50 p-4 text-red-700">{error}</div>;
  }

  if (!payment) {
    return <div className="rounded-2xl border border-slate-200 bg-white p-4 text-slate-600">Payment not found.</div>;
  }

  return (
    <div>
      <h1 className="mb-6 text-3xl font-bold text-gray-800">Payment Details</h1>

      <div className="grid gap-6 lg:grid-cols-2">
        <DetailCard
          title="Reference"
          rows={[
            ['Reference No', payment.reference_no || '-'],
            ['Fee Year', payment.fee_year || '-'],
            ['Fee Type', payment.fee_type || '-'],
            ['Account', payment.account || '-'],
          ]}
        />

        <DetailCard
          title="Amount & Status"
          rows={[
            ['Amount', `TZS ${Number(payment.fee || 0).toLocaleString()}`],
            ['Status', String(payment.paystatus || 'PENDING').toUpperCase()],
            ['Payment Plan', formatInstallment(payment.installment)],
            ['Due Date', payment.duedate || '-'],
          ]}
        />
      </div>
    </div>
  );
}

function DetailCard({ title, rows }) {
  return (
    <div className="rounded-[28px] border border-slate-200/70 bg-white p-6 shadow-[0_18px_48px_rgba(15,23,42,0.08)]">
      <h2 className="text-xl font-semibold text-slate-900">{title}</h2>
      <div className="mt-4 space-y-3">
        {rows.map(([label, value]) => (
          <div key={label} className="flex items-center justify-between rounded-2xl bg-slate-50 px-4 py-3">
            <span className="text-sm font-medium text-slate-500">{label}</span>
            <span className="text-sm font-semibold text-slate-900">{value}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
