import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useAuthStore } from '../stores/authStore';
import { membersAPI, paymentsAPI } from '../services/api';

function getStatusTone(paystatus) {
  return String(paystatus || '').toUpperCase() === 'PAID'
    ? 'bg-emerald-100 text-emerald-700'
    : 'bg-amber-100 text-amber-700';
}

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

export default function Payments() {
  const { user } = useAuthStore();
  const ITEMS_PER_PAGE = 8;
  const [payments, setPayments] = useState([]);
  const [loading, setLoading] = useState(true);
  const [status, setStatus] = useState('');
  const [error, setError] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [summary, setSummary] = useState({
    total_paid: 0,
    total_outstanding: 0,
  });

  const totalPages = Math.max(1, Math.ceil(payments.length / ITEMS_PER_PAGE));
  const paginatedPayments = payments.slice((currentPage - 1) * ITEMS_PER_PAGE, currentPage * ITEMS_PER_PAGE);

  useEffect(() => {
    const fetchPayments = async () => {
      setLoading(true);
      setError('');

      try {
        if (user?.role === 'member') {
          const member = await membersAPI.me();
          const response = await paymentsAPI.getByMember(member.id);
          const invoices = response.invoices || [];
          const filtered = status
            ? invoices.filter((payment) =>
                status === 'PAID'
                  ? String(payment.paystatus || '').toUpperCase() === 'PAID'
                  : String(payment.paystatus || '').toUpperCase() !== 'PAID'
              )
            : invoices;

          setPayments(filtered);
          setSummary({
            total_paid: Number(response.total_paid || 0),
            total_outstanding: Number(response.total_outstanding || 0),
          });
          return;
        }

        if (user && ['admin', 'finance'].includes(user.role)) {
          const response = await paymentsAPI.list(1, 50, status);
          setPayments(response.invoices || []);
          return;
        }

        setError('You are not authorized to view payments.');
      } catch (fetchError) {
        setError(fetchError.response?.data?.error || 'Failed to fetch payments.');
      } finally {
        setLoading(false);
      }
    };

    fetchPayments();
  }, [status, user]);

  useEffect(() => {
    setCurrentPage(1);
  }, [status, user]);

  useEffect(() => {
    if (currentPage > totalPages) {
      setCurrentPage(totalPages);
    }
  }, [currentPage, totalPages]);

  return (
    <div>
      <div className="mb-6 flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-3xl font-bold text-gray-800">Payments</h1>
        </div>

        <select
          value={status}
          onChange={(event) => setStatus(event.target.value)}
          className="rounded-2xl border border-slate-200 bg-white px-4 py-3 text-sm text-slate-700 shadow-sm"
        >
          <option value="">All Status</option>
          <option value="PENDING">Pending</option>
          <option value="PAID">Paid</option>
        </select>
      </div>

      {user?.role === 'member' && !loading && !error && (
        <div className="mb-6 grid gap-4 md:grid-cols-2">
          <SummaryPanel
            title="Total Paid"
            value={`TZS ${Number(summary.total_paid).toLocaleString()}`}
            tone="emerald"
          />
          <SummaryPanel
            title="Outstanding"
            value={`TZS ${Number(summary.total_outstanding).toLocaleString()}`}
            tone="amber"
          />
        </div>
      )}

      {loading && <p className="text-gray-600">Loading...</p>}

      {error && !loading && (
        <div className="mb-6 rounded-2xl border border-red-200 bg-red-50 p-4 text-red-700">
          {error}
        </div>
      )}

      {!loading && !error && (
        <div className="overflow-hidden rounded-[28px] bg-white shadow-[0_20px_50px_rgba(15,23,42,0.08)]">
          {payments.length > 0 ? (
            <>
              <div className="space-y-4 p-4 md:hidden">
                {paginatedPayments.map((payment) => (
                  <div key={payment.id} className="rounded-[22px] border border-slate-200/70 bg-slate-50/90 p-4">
                    <div className="flex items-start justify-between gap-3">
                      <div>
                        <p className="text-sm font-semibold text-slate-900">{payment.reference_no}</p>
                        <p className="mt-1 text-xs uppercase tracking-[0.18em] text-slate-500">{payment.fee_type || 'Annual Fee'}</p>
                      </div>
                      <span className={`rounded-full px-3 py-1 text-[11px] font-semibold ${getStatusTone(payment.paystatus)}`}>
                        {String(payment.paystatus || 'PENDING').toUpperCase()}
                      </span>
                    </div>

                    <div className="mt-4 grid gap-3 text-sm text-slate-600">
                      <PaymentRow label="Year" value={payment.fee_year || '-'} />
                      <PaymentRow label="Amount" value={`TZS ${Number(payment.fee || 0).toLocaleString()}`} />
                      <PaymentRow label="Payment Plan" value={formatInstallment(payment.installment)} />
                      <PaymentRow label="Due Date" value={payment.duedate || '-'} />
                    </div>

                    <Link
                      to={`/payments/${payment.id}`}
                      className="mt-4 inline-flex rounded-2xl bg-slate-900 px-4 py-2.5 text-sm font-medium text-white"
                    >
                      View Payment
                    </Link>
                  </div>
                ))}
              </div>

              <div className="hidden overflow-x-auto md:block">
                <table className="w-full">
                  <thead className="border-b bg-slate-100">
                    <tr>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Reference No</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Year</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Type</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Amount</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Payment Plan</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Status</th>
                      <th className="px-4 py-3 text-left font-semibold text-slate-700">Action</th>
                    </tr>
                  </thead>
                  <tbody>
                    {paginatedPayments.map((payment) => (
                      <tr key={payment.id} className="border-b last:border-b-0 hover:bg-slate-50">
                        <td className="px-4 py-3 font-mono text-sm">{payment.reference_no}</td>
                        <td className="px-4 py-3">{payment.fee_year}</td>
                        <td className="px-4 py-3">{payment.fee_type || 'Annual Fee'}</td>
                        <td className="px-4 py-3">TZS {Number(payment.fee || 0).toLocaleString()}</td>
                        <td className="px-4 py-3">{formatInstallment(payment.installment)}</td>
                        <td className="px-4 py-3">
                          <span className={`rounded-full px-3 py-1 text-xs font-semibold ${getStatusTone(payment.paystatus)}`}>
                            {String(payment.paystatus || 'PENDING').toUpperCase()}
                          </span>
                        </td>
                        <td className="px-4 py-3">
                          <Link to={`/payments/${payment.id}`} className="font-medium text-blue-600 hover:underline">
                            View
                          </Link>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>

              {totalPages > 1 && (
                <div className="flex items-center justify-between border-t border-slate-100 px-4 py-4 md:px-6">
                  <p className="text-sm text-slate-500">
                    Page {currentPage} of {totalPages}
                  </p>
                  <div className="flex gap-3">
                    <button
                      type="button"
                      onClick={() => setCurrentPage((page) => Math.max(1, page - 1))}
                      disabled={currentPage === 1}
                      className="rounded-2xl bg-slate-100 px-4 py-2 text-sm font-medium text-slate-700 transition hover:bg-slate-200 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      Previous
                    </button>
                    <button
                      type="button"
                      onClick={() => setCurrentPage((page) => Math.min(totalPages, page + 1))}
                      disabled={currentPage === totalPages}
                      className="rounded-2xl bg-slate-900 px-4 py-2 text-sm font-medium text-white transition hover:bg-slate-800 disabled:cursor-not-allowed disabled:opacity-50"
                    >
                      Next
                    </button>
                  </div>
                </div>
              )}
            </>
          ) : (
            <div className="p-8 text-center text-gray-600">No payments found.</div>
          )}
        </div>
      )}
    </div>
  );
}

function SummaryPanel({ title, value, tone }) {
  const tones = {
    emerald: 'border-emerald-200 bg-emerald-50 text-emerald-800',
    amber: 'border-amber-200 bg-amber-50 text-amber-800',
  };

  return (
    <div className={`rounded-[24px] border p-5 ${tones[tone]}`}>
      <p className="text-sm font-semibold">{title}</p>
      <p className="mt-2 text-2xl font-bold">{value}</p>
    </div>
  );
}

function PaymentRow({ label, value }) {
  return (
    <div className="flex items-center justify-between rounded-2xl bg-white px-3 py-3">
      <span className="text-xs font-semibold uppercase tracking-[0.16em] text-slate-400">{label}</span>
      <span className="ml-4 text-right text-sm font-medium text-slate-700">{value}</span>
    </div>
  );
}
