'use client';

import { useState } from 'react';
import { Download, CheckCircle, Loader2 } from 'lucide-react';
import Link from 'next/link';
import toast from 'react-hot-toast';

interface Payment {
  id: string;
  order_number: string;
  total_amount: string;
  payment_status: string;
  payment_method: string;
  transaction_id: string;
  created_at: string;
}

function PaymentRow({ payment }: { payment: Payment }) {
  const [isDownloading, setIsDownloading] = useState(false);

  const handleDownloadInvoice = async () => {
    setIsDownloading(true);
    try {
      const response = await fetch(`/api/frontend/dashboard/orders/${payment.id}/invoice`);
      
      if (!response.ok) {
        throw new Error('Failed to download invoice');
      }
      
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `invoice-${payment.order_number}.pdf`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      window.URL.revokeObjectURL(url);
      toast.success('Invoice downloaded successfully');
    } catch (error) {
      console.error('Error downloading invoice:', error);
      toast.error('Failed to download invoice');
    } finally {
      setIsDownloading(false);
    }
  };

  return (
    <tr className="hover:bg-gray-50 transition-colors">
      <td className="px-6 py-4">
        <Link
          href={`/dashboard/orders/${payment.id}`}
          className="text-sm font-medium text-[#0066FF] hover:underline"
        >
          {payment.order_number}
        </Link>
       </td>
      <td className="px-6 py-4">
        <span className="text-sm text-gray-600">
          {new Date(payment.created_at).toLocaleDateString()}
        </span>
       </td>
      <td className="px-6 py-4">
        <span className="text-sm font-medium text-gray-900">
          ${parseFloat(payment.total_amount).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}
        </span>
       </td>
      <td className="px-6 py-4">
        <span className="text-sm text-gray-600 capitalize">
          {payment.payment_method || 'N/A'}
        </span>
       </td>
      <td className="px-6 py-4">
        <span className="text-sm text-gray-600 font-mono">
          {payment.transaction_id || 'N/A'}
        </span>
       </td>
      <td className="px-6 py-4">
        <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-green-100 text-green-700">
          <CheckCircle className="h-3 w-3 mr-1" />
          Paid
        </span>
       </td>
      <td className="px-6 py-4 text-right">
        <button
          onClick={handleDownloadInvoice}
          disabled={isDownloading}
          className="text-gray-400 hover:text-[#0066FF] transition-colors disabled:opacity-50"
          title="Download Invoice"
        >
          {isDownloading ? (
            <Loader2 className="h-4 w-4 animate-spin" />
          ) : (
            <Download className="h-4 w-4" />
          )}
        </button>
       </td>
    </tr>
  );
}

interface PaymentsClientProps {
  payments: Payment[];
}

export default function PaymentsClient({ payments }: PaymentsClientProps) {
  return (
    <div className="bg-white rounded-2xl border border-gray-200 overflow-hidden">
      <div className="overflow-x-auto">
        <table className="w-full">
          <thead className="bg-gray-50 border-b border-gray-200">
            <tr>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Order #
              </th>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Date
              </th>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Amount
              </th>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Method
              </th>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Transaction ID
              </th>
              <th className="text-left px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Status
              </th>
              <th className="text-right px-6 py-3 text-xs font-medium text-gray-500 uppercase tracking-wider">
                Invoice
              </th>
            </tr>
          </thead>
          <tbody className="divide-y divide-gray-200">
            {payments.length === 0 ? (
              <tr>
                <td colSpan={7} className="text-center py-12">
                  <p className="text-gray-500">No payment history found</p>
                  <Link
                    href="/websites"
                    className="text-[#0066FF] text-sm mt-2 inline-block hover:underline"
                  >
                    Place your first order →
                  </Link>
                </td>
              </tr>
            ) : (
              payments.map((payment) => (
                <PaymentRow key={payment.id} payment={payment} />
              ))
            )}
          </tbody>
        </table>
      </div>
    </div>
  );
}