'use client';

import { useState, useEffect } from 'react';

interface Props {
  companyId?: string;
  selectedCompany: 'rmp' | 'jtr';
}

function fmt(n: number) {
  return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(n);
}

const STATUS_COLORS: Record<string, string> = {
  succeeded: 'bg-green-900 text-green-300',
  failed: 'bg-red-900 text-red-300',
  pending: 'bg-yellow-900 text-yellow-300',
  refunded: 'bg-gray-700 text-gray-300',
  disputed: 'bg-orange-900 text-orange-300',
};

export default function PaymentsTab({ companyId, selectedCompany }: Props) {
  const [payments, setPayments] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    setLoading(true);
    const params = companyId ? `?companyId=${companyId}` : '';
    fetch(`/api/billing/payments${params}`)
      .then(r => r.json())
      .then(d => setPayments(d.data || []))
      .finally(() => setLoading(false));
  }, [companyId]);

  const disputed = payments.filter(p => p.status === 'disputed');
  const failed = payments.filter(p => p.status === 'failed');

  return (
    <div className="space-y-4">
      {/* Alerts */}
      {disputed.length > 0 && (
        <div className="bg-orange-900/30 border border-orange-700 rounded-xl p-4 flex items-start gap-3">
          <span className="text-orange-400 text-lg">⚠</span>
          <div>
            <p className="text-orange-300 font-semibold text-sm">Stripe Dispute Alert</p>
            <p className="text-orange-400 text-xs mt-0.5">{disputed.length} active dispute{disputed.length > 1 ? 's' : ''} require your attention.</p>
          </div>
        </div>
      )}
      {failed.length > 0 && (
        <div className="bg-red-900/20 border border-red-800 rounded-xl p-4 flex items-start gap-3">
          <span className="text-red-400 text-lg">✕</span>
          <div>
            <p className="text-red-300 font-semibold text-sm">Failed Payments</p>
            <p className="text-red-400 text-xs mt-0.5">{failed.length} payment{failed.length > 1 ? 's' : ''} failed recently.</p>
          </div>
        </div>
      )}

      {/* Stripe Connection Notice */}
      <div className="bg-gray-900 border border-gray-700 rounded-xl p-4 flex items-center gap-3">
        <div className="w-8 h-8 bg-indigo-900/50 rounded-lg flex items-center justify-center">
          <svg className="w-4 h-4 text-indigo-400" fill="currentColor" viewBox="0 0 24 24">
            <path d="M13.976 9.15c-2.172-.806-3.356-1.426-3.356-2.409 0-.831.683-1.305 1.901-1.305 2.227 0 4.515.858 6.09 1.631l.89-5.494C18.252.975 15.697 0 12.165 0 9.667 0 7.589.654 6.104 1.872 4.56 3.147 3.757 4.992 3.757 7.218c0 4.039 2.467 5.76 6.476 7.219 2.585.92 3.445 1.574 3.445 2.583 0 .98-.84 1.545-2.354 1.545-1.875 0-4.965-.921-6.99-2.109l-.9 5.555C5.175 22.99 8.385 24 11.714 24c2.641 0 4.843-.624 6.328-1.813 1.664-1.305 2.525-3.236 2.525-5.732 0-4.128-2.524-5.851-6.591-7.305z"/>
          </svg>
        </div>
        <div>
          <p className="text-sm font-medium text-gray-200">
            Stripe (Relevant Media Properties)
          </p>
          <p className="text-xs text-gray-500 mt-0.5">
            Connect Stripe account in Settings → Stripe Settings to enable payment collection.
          </p>
        </div>
        <span className="ml-auto px-2 py-1 bg-yellow-900/50 text-yellow-300 rounded text-xs">Not Connected</span>
      </div>

      {/* Payments Table */}
      <div className="bg-gray-900 border border-gray-800 rounded-xl overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="border-b border-gray-800 text-gray-400 text-xs uppercase tracking-wide">
                <th className="text-left px-4 py-3">Date</th>
                <th className="text-left px-4 py-3">Client</th>
                <th className="text-left px-4 py-3">Invoice #</th>
                <th className="text-left px-4 py-3">Amount</th>
                <th className="text-left px-4 py-3">Method</th>
                <th className="text-left px-4 py-3">Status</th>
                <th className="text-left px-4 py-3">Stripe ID</th>
              </tr>
            </thead>
            <tbody>
              {loading ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">Loading...</td></tr>
              ) : payments.length === 0 ? (
                <tr><td colSpan={7} className="text-center py-12 text-gray-500">No payments recorded yet.</td></tr>
              ) : payments.map(p => (
                <tr key={p.id} className={`border-b border-gray-800 hover:bg-gray-800/50 transition-colors ${p.status === 'failed' || p.status === 'disputed' ? 'bg-red-950/20' : ''}`}>
                  <td className="px-4 py-3 text-gray-400">{p.payment_date || '—'}</td>
                  <td className="px-4 py-3 text-gray-200">{p.billing_clients?.name || '—'}</td>
                  <td className="px-4 py-3 font-mono text-blue-400 text-xs">{p.billing_invoices?.invoice_number || '—'}</td>
                  <td className="px-4 py-3 font-medium text-gray-200">{fmt(p.amount || 0)}</td>
                  <td className="px-4 py-3 text-gray-400 capitalize">{p.payment_method || '—'}</td>
                  <td className="px-4 py-3">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${STATUS_COLORS[p.status] || 'bg-gray-700 text-gray-300'}`}>
                      {p.status}
                    </span>
                  </td>
                  <td className="px-4 py-3 font-mono text-xs text-gray-500 truncate max-w-[120px]">
                    {p.stripe_payment_intent_id || p.stripe_charge_id || '—'}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}
