'use client';

import { useState, useEffect } from 'react';
import { ccApi, AdminPayment } from '@/lib/api';

export default function AdminPaymentsPage() {
  const [payments, setPayments] = useState<AdminPayment[]>([]);
  const [pendingPayments, setPendingPayments] = useState<AdminPayment[]>([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize] = useState(20);
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [selectedPayment, setSelectedPayment] = useState<AdminPayment | null>(null);
  const [adminNote, setAdminNote] = useState('');
  const [processing, setProcessing] = useState(false);

  useEffect(() => {
    loadData();
  }, [page, statusFilter]);

  const loadData = async () => {
    try {
      setLoading(true);
      const [pendingData, allData] = await Promise.all([
        ccApi.adminGetPendingPayments(),
        ccApi.adminGetAllPayments({ status: statusFilter || undefined, page, page_size: pageSize }),
      ]);
      setPendingPayments(pendingData);
      setPayments(allData.payments);
      setTotal(allData.total);
    } catch (error) {
      console.error('Failed to load payments:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async (approved: boolean) => {
    if (!selectedPayment) return;

    setProcessing(true);
    try {
      await ccApi.adminVerifyPayment(selectedPayment.id, approved, adminNote);
      setSelectedPayment(null);
      setAdminNote('');
      loadData();
    } catch (error: any) {
      alert(error.response?.data?.detail || 'Failed to process payment');
    } finally {
      setProcessing(false);
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'completed':
        return <span className="px-2 py-1 bg-green-100 text-green-700 rounded-full text-xs">Completed</span>;
      case 'pending':
        return <span className="px-2 py-1 bg-yellow-100 text-yellow-700 rounded-full text-xs">Pending</span>;
      case 'rejected':
        return <span className="px-2 py-1 bg-red-100 text-red-700 rounded-full text-xs">Rejected</span>;
      default:
        return <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded-full text-xs">{status}</span>;
    }
  };

  const getMethodBadge = (method: string) => {
    switch (method) {
      case 'usdc':
        return <span className="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs">USDC</span>;
      case 'bank_transfer':
        return <span className="px-2 py-1 bg-green-100 text-green-700 rounded text-xs">Bank</span>;
      case 'card':
        return <span className="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs">Card</span>;
      default:
        return <span className="px-2 py-1 bg-gray-100 text-gray-700 rounded text-xs">{method}</span>;
    }
  };

  const formatDate = (dateStr?: string) => {
    if (!dateStr) return '-';
    return new Date(dateStr).toLocaleString('ko-KR');
  };

  const totalPages = Math.ceil(total / pageSize);

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold text-gray-800">Payment Management</h1>
        <button
          onClick={loadData}
          className="px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg text-sm"
        >
          Refresh
        </button>
      </div>

      {/* Pending Payments Alert */}
      {pendingPayments.length > 0 && (
        <div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
          <h3 className="font-semibold text-amber-800 mb-3">
            Pending Payments ({pendingPayments.length})
          </h3>
          <div className="space-y-2">
            {pendingPayments.slice(0, 5).map((payment) => (
              <div
                key={payment.id}
                className="flex items-center justify-between p-3 bg-white rounded-lg cursor-pointer hover:shadow"
                onClick={() => setSelectedPayment(payment)}
              >
                <div className="flex items-center gap-3">
                  {getMethodBadge(payment.payment_method)}
                  <div>
                    <p className="font-medium">{payment.user_email}</p>
                    <p className="text-sm text-gray-500">
                      {payment.amount} {payment.currency} = {payment.cc_amount} CC
                    </p>
                  </div>
                </div>
                <div className="text-right">
                  <p className="text-sm text-gray-500">{formatDate(payment.created_at)}</p>
                  <button className="text-primary-600 text-sm hover:underline">Review</button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Filters */}
      <div className="bg-white rounded-xl shadow-sm p-4">
        <div className="flex flex-wrap gap-4">
          <select
            value={statusFilter}
            onChange={(e) => {
              setStatusFilter(e.target.value);
              setPage(1);
            }}
            className="px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
          >
            <option value="">All Status</option>
            <option value="pending">Pending</option>
            <option value="completed">Completed</option>
            <option value="rejected">Rejected</option>
          </select>
          <span className="text-gray-500 self-center">Total: {total} payments</span>
        </div>
      </div>

      {/* Payments Table */}
      <div className="bg-white rounded-xl shadow-sm overflow-hidden">
        {loading ? (
          <div className="flex items-center justify-center h-64">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-500"></div>
          </div>
        ) : payments.length === 0 ? (
          <div className="text-center py-12 text-gray-500">No payments found</div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">User</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Amount</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">CC</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Method</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">TX Hash</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Date</th>
                  <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-gray-200">
                {payments.map((payment) => (
                  <tr key={payment.id} className="hover:bg-gray-50">
                    <td className="px-4 py-3 text-sm text-gray-800">{payment.id}</td>
                    <td className="px-4 py-3 text-sm">
                      <div>{payment.user_email}</div>
                      <div className="text-xs text-gray-500">{payment.user_name || '-'}</div>
                    </td>
                    <td className="px-4 py-3 text-sm font-medium">
                      {payment.amount} {payment.currency}
                    </td>
                    <td className="px-4 py-3 text-sm text-blue-600 font-semibold">
                      +{payment.cc_amount} CC
                    </td>
                    <td className="px-4 py-3 text-sm">{getMethodBadge(payment.payment_method)}</td>
                    <td className="px-4 py-3 text-sm">
                      {payment.transaction_id ? (
                        <code className="text-xs bg-gray-100 px-2 py-1 rounded truncate max-w-[100px] block">
                          {payment.transaction_id.slice(0, 10)}...
                        </code>
                      ) : (
                        '-'
                      )}
                    </td>
                    <td className="px-4 py-3 text-sm">{getStatusBadge(payment.status)}</td>
                    <td className="px-4 py-3 text-sm text-gray-500">{formatDate(payment.created_at)}</td>
                    <td className="px-4 py-3 text-sm">
                      {payment.status === 'pending' ? (
                        <button
                          onClick={() => setSelectedPayment(payment)}
                          className="px-3 py-1 bg-primary-500 text-white rounded hover:bg-primary-600 text-xs"
                        >
                          Review
                        </button>
                      ) : (
                        <button
                          onClick={() => setSelectedPayment(payment)}
                          className="px-3 py-1 border rounded hover:bg-gray-50 text-xs"
                        >
                          View
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* Pagination */}
        {totalPages > 1 && (
          <div className="flex items-center justify-between px-4 py-3 border-t">
            <div className="text-sm text-gray-500">
              Page {page} of {totalPages}
            </div>
            <div className="flex gap-2">
              <button
                onClick={() => setPage((p) => Math.max(1, p - 1))}
                disabled={page === 1}
                className="px-3 py-1 border rounded hover:bg-gray-50 disabled:opacity-50"
              >
                Previous
              </button>
              <button
                onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
                disabled={page === totalPages}
                className="px-3 py-1 border rounded hover:bg-gray-50 disabled:opacity-50"
              >
                Next
              </button>
            </div>
          </div>
        )}
      </div>

      {/* Payment Detail Modal */}
      {selectedPayment && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
          <div className="bg-white rounded-xl p-6 w-full max-w-lg mx-4 max-h-[90vh] overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-lg font-semibold">Payment Details</h3>
              <button
                onClick={() => {
                  setSelectedPayment(null);
                  setAdminNote('');
                }}
                className="text-gray-400 hover:text-gray-600"
              >
                ✕
              </button>
            </div>

            <div className="space-y-4">
              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500">Payment ID</p>
                  <p className="font-medium">{selectedPayment.id}</p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">Status</p>
                  <p>{getStatusBadge(selectedPayment.status)}</p>
                </div>
              </div>

              <div>
                <p className="text-sm text-gray-500">User</p>
                <p className="font-medium">{selectedPayment.user_email}</p>
                <p className="text-sm text-gray-500">{selectedPayment.user_name || 'No name'}</p>
              </div>

              <div className="grid grid-cols-2 gap-4">
                <div>
                  <p className="text-sm text-gray-500">Amount</p>
                  <p className="font-medium text-lg">
                    {selectedPayment.amount} {selectedPayment.currency}
                  </p>
                </div>
                <div>
                  <p className="text-sm text-gray-500">CC to Credit</p>
                  <p className="font-medium text-lg text-blue-600">+{selectedPayment.cc_amount} CC</p>
                </div>
              </div>

              <div>
                <p className="text-sm text-gray-500">Payment Method</p>
                <p>{getMethodBadge(selectedPayment.payment_method)}</p>
              </div>

              {selectedPayment.transaction_id && (
                <div>
                  <p className="text-sm text-gray-500">Transaction Hash</p>
                  <code className="text-xs bg-gray-100 px-2 py-1 rounded block break-all">
                    {selectedPayment.transaction_id}
                  </code>
                  {selectedPayment.payment_method === 'usdc' && (
                    <a
                      href={`https://polygonscan.com/tx/${selectedPayment.transaction_id}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs text-primary-600 hover:underline mt-1 inline-block"
                    >
                      View on PolygonScan
                    </a>
                  )}
                </div>
              )}

              {selectedPayment.wallet_address && (
                <div>
                  <p className="text-sm text-gray-500">User Wallet (for refund)</p>
                  <code className="text-xs bg-gray-100 px-2 py-1 rounded block break-all">
                    {selectedPayment.wallet_address}
                  </code>
                </div>
              )}

              <div>
                <p className="text-sm text-gray-500">Submitted At</p>
                <p>{formatDate(selectedPayment.created_at)}</p>
              </div>

              {selectedPayment.verified_at && (
                <div>
                  <p className="text-sm text-gray-500">Verified At</p>
                  <p>{formatDate(selectedPayment.verified_at)}</p>
                </div>
              )}

              {selectedPayment.admin_note && (
                <div>
                  <p className="text-sm text-gray-500">Admin Note</p>
                  <p className="bg-gray-50 p-2 rounded">{selectedPayment.admin_note}</p>
                </div>
              )}

              {selectedPayment.status === 'pending' && (
                <>
                  <div>
                    <label className="block text-sm font-medium text-gray-700 mb-1">
                      Admin Note (optional)
                    </label>
                    <textarea
                      value={adminNote}
                      onChange={(e) => setAdminNote(e.target.value)}
                      placeholder="Add a note..."
                      className="w-full px-4 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
                      rows={2}
                    />
                  </div>

                  <div className="flex gap-3">
                    <button
                      onClick={() => handleVerify(false)}
                      disabled={processing}
                      className="flex-1 px-4 py-2 border border-red-500 text-red-600 rounded-lg hover:bg-red-50 disabled:opacity-50"
                    >
                      {processing ? 'Processing...' : 'Reject'}
                    </button>
                    <button
                      onClick={() => handleVerify(true)}
                      disabled={processing}
                      className="flex-1 px-4 py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 disabled:opacity-50"
                    >
                      {processing ? 'Processing...' : 'Approve'}
                    </button>
                  </div>
                </>
              )}

              {selectedPayment.status !== 'pending' && (
                <button
                  onClick={() => {
                    setSelectedPayment(null);
                    setAdminNote('');
                  }}
                  className="w-full px-4 py-2 border rounded-lg hover:bg-gray-50"
                >
                  Close
                </button>
              )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
