'use client';

import { useEffect, useState, useCallback } from 'react';
import toast from 'react-hot-toast';
import { useCurrencyStore } from '@/store/currencyStore';
import { getApiErrorMessage } from '@/lib/utils/apiError';

interface WithdrawalRequest {
  id: string;
  user_id: string;
  user_name: string;
  user_email: string;
  amount: number;
  bank_name: string;
  account_title: string;
  account_number: string;
  status: 'pending' | 'approved' | 'rejected' | 'paid';
  admin_notes: string | null;
  requested_at: string;
  processed_at: string | null;
  prior_paid_count: number;
}

interface WithdrawalRequestsTableProps {
  canUpdate: boolean;
}

const STATUS_STYLE: Record<WithdrawalRequest['status'], { bg: string; color: string }> = {
  pending: { bg: 'var(--color-warning-light)', color: 'var(--color-warning)' },
  approved: { bg: 'var(--color-info-light)', color: 'var(--color-info)' },
  paid: { bg: 'var(--color-success-light)', color: 'var(--color-success)' },
  rejected: { bg: 'var(--color-danger-light)', color: 'var(--color-danger)' },
};

const FILTERS: Array<WithdrawalRequest['status'] | 'all'> = ['all', 'pending', 'approved', 'paid', 'rejected'];

export default function WithdrawalRequestsTable({ canUpdate }: WithdrawalRequestsTableProps) {
  const formatAmount = useCurrencyStore((s) => s.formatAmount);
  const [filter, setFilter] = useState<(typeof FILTERS)[number]>('pending');
  const [requests, setRequests] = useState<WithdrawalRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [notesDraft, setNotesDraft] = useState<Record<string, string>>({});

  const load = useCallback(() => {
    const params = new URLSearchParams({ limit: '50' });
    if (filter !== 'all') params.set('status', filter);
    fetch(`/api/withdrawal-requests?${params}`, { credentials: 'include' })
      .then((res) => res.json())
      .then((data) => {
        if (data.success) setRequests(data.data.requests);
      })
      .finally(() => setLoading(false));
  }, [filter]);

  useEffect(() => { load(); }, [load]);

  const handleAction = async (id: string, status: 'approved' | 'rejected' | 'paid') => {
    setBusyId(id);
    try {
      const res = await fetch(`/api/withdrawal-requests/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ status, admin_notes: notesDraft[id] || undefined }),
      });
      const data = await res.json();
      if (!res.ok || !data.success) {
        toast.error(getApiErrorMessage(data, 'Failed to update withdrawal request'));
        return;
      }
      toast.success(data.message);
      load();
    } catch {
      toast.error('Network error');
    } finally {
      setBusyId(null);
    }
  };

  return (
    <div>
      <div className="flex flex-wrap gap-2 mb-4">
        {FILTERS.map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className="px-3 py-1.5 rounded-full text-sm font-medium transition-all capitalize"
            style={{
              background: filter === f ? 'var(--color-cta)' : 'var(--color-surface-alt)',
              color: filter === f ? 'white' : 'var(--color-text)',
              border: '1px solid var(--color-border)',
            }}
          >
            {f}
          </button>
        ))}
      </div>

      {loading ? (
        <div className="space-y-3">
          {Array.from({ length: 3 }).map((_, i) => (
            <div key={i} className="skeleton h-20 w-full rounded-lg" />
          ))}
        </div>
      ) : requests.length === 0 ? (
        <p className="text-sm text-center py-12" style={{ color: 'var(--color-text-tertiary)' }}>
          No withdrawal requests {filter !== 'all' ? `with status "${filter}"` : ''}.
        </p>
      ) : (
        <div className="space-y-3">
          {requests.map((r) => (
            <div
              key={r.id}
              className="rounded-lg p-4"
              style={{ background: 'var(--color-surface)', border: '1px solid var(--color-border)' }}
            >
              <div className="flex flex-wrap justify-between items-start gap-3">
                <div>
                  <p className="font-medium" style={{ color: 'var(--color-text)' }}>{r.user_name}</p>
                  <p className="text-xs" style={{ color: 'var(--color-text-tertiary)' }}>{r.user_email}</p>
                  <p className="text-xs mt-1" style={{ color: 'var(--color-text-tertiary)' }}>
                    {new Date(r.requested_at).toLocaleString()} · {r.prior_paid_count} prior payout{r.prior_paid_count === 1 ? '' : 's'}
                  </p>
                </div>
                <div className="text-right">
                  <p className="text-lg font-bold" style={{ color: 'var(--color-cta)' }}>{formatAmount(r.amount)}</p>
                  <span
                    className="inline-block text-xs px-2 py-0.5 rounded-full font-medium capitalize"
                    style={{ background: STATUS_STYLE[r.status].bg, color: STATUS_STYLE[r.status].color }}
                  >
                    {r.status}
                  </span>
                </div>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 mt-3 text-sm" style={{ color: 'var(--color-text-secondary)' }}>
                <div><span style={{ color: 'var(--color-text-tertiary)' }}>Bank:</span> {r.bank_name}</div>
                <div><span style={{ color: 'var(--color-text-tertiary)' }}>Account Title:</span> {r.account_title}</div>
                <div><span style={{ color: 'var(--color-text-tertiary)' }}>Account #:</span> {r.account_number}</div>
              </div>

              {r.admin_notes && (
                <p className="text-xs mt-2 italic" style={{ color: 'var(--color-text-tertiary)' }}>
                  Note: {r.admin_notes}
                </p>
              )}

              {canUpdate && (r.status === 'pending' || r.status === 'approved') && (
                <div className="flex flex-wrap items-center gap-2 mt-3 pt-3" style={{ borderTop: '1px solid var(--color-border)' }}>
                  <input
                    type="text"
                    placeholder="Note (optional)"
                    value={notesDraft[r.id] ?? ''}
                    onChange={(e) => setNotesDraft((prev) => ({ ...prev, [r.id]: e.target.value }))}
                    className="flex-1 min-w-[160px] px-3 py-1.5 rounded-lg text-sm outline-none"
                    style={{ background: 'var(--color-surface-alt)', border: '1px solid var(--color-border)', color: 'var(--color-text)' }}
                  />
                  {r.status === 'pending' && (
                    <>
                      <button
                        disabled={busyId === r.id}
                        onClick={() => handleAction(r.id, 'approved')}
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                        style={{ background: 'var(--color-success)' }}
                      >
                        Approve
                      </button>
                      <button
                        disabled={busyId === r.id}
                        onClick={() => handleAction(r.id, 'rejected')}
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                        style={{ background: 'var(--color-danger)' }}
                      >
                        Reject
                      </button>
                    </>
                  )}
                  {r.status === 'approved' && (
                    <>
                      <button
                        disabled={busyId === r.id}
                        onClick={() => handleAction(r.id, 'paid')}
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                        style={{ background: 'var(--color-success)' }}
                      >
                        Mark as Paid
                      </button>
                      <button
                        disabled={busyId === r.id}
                        onClick={() => handleAction(r.id, 'rejected')}
                        className="px-3 py-1.5 rounded-lg text-sm font-medium text-white disabled:opacity-50"
                        style={{ background: 'var(--color-danger)' }}
                      >
                        Reject
                      </button>
                    </>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
